zoukankan      html  css  js  c++  java
  • C++ 流操作符重载函数

    1. 问题

      在C++中,在进行输入输出操作时,我们首先会想到用cout, cin这两个库操作语句来实现,比如

        cout << 8 << "hello world!" << endl;

        cin >> s;

      cout,cin分别是库ostream, istream里的类对象

      如果想要cout,cin来输出或输入一个类对象,这样的需求它能满足吗?很显然,原来的cout不太可能满足直接输入输出一个我们自定义的类对象,

      但是只要我们对<<, >>操作符进行重载就可以让它处理自定义的类对象了。

    2. 实现

      有一复数类:

    class Complex {
         priate:
               int real;
               int imag;
         public:
               Complex(int r=0, int i=0):real(r),imag(i) {
                      cout << real << " + " << imag << "i" ;
                      cout << "complex class constructed."
               } 
    }

    int main() {
          Complex c; // output : 0+0i, complex class constructed.
          cout << c ; // error

          return 0;
    }

      之所以上面main函数中 cout << c会出错,是因为 cout本身不支持类对象的处理,如果要让它同样能打印类对象,必须得重载操作符<<.

    #include <iostream>
    #include <string>
    
    class Complex {
         priate:
               int real;
               int imag;
         public:
               Complex(int r=0, int i=0):real(r),imag(i) {
                      cout << real << " + " << imag << "i" ;
                      cout << "complex class constructed."
               } 
               // overload global function
               friend ostream & operator<<(ostream & o, const Complex & c);
               friend istream & operator >> (istream & i, Complex & c);
    }
    
    ostream & operator<<(ostream & o, const Complex & c) {
            o<< c.real << "+" << c.imag << "i";
            return o;
    }
    
    istream & operator >> (istream & i, Complex & c){
           string  s;
           i >> s;   // simillar to cin >> s; input string format like as a+bi
           ...  // parse s and get the real and imag
           c. real = real;
           c.imag = imag;
           return i;
    }

      重载了操作符 <<, >> 运算后, 就可以对类Complex直接进行 输入输出操作了,比如

    int main{
           Complex c, c1;
           cin >> c;   //input : 3+4i
           cout << c <<";" << c1 << " complex output."; // output : 3+4i; 0+0i complex output.
    }
  • 相关阅读:
    STM32-使用软件模拟I2C读写外部EEPROM(AT24C02)
    STM32-软件模拟I2C
    STM32_使用DAC输出三角波
    VS常用快捷键
    C语言volatile关键字在单片机中的作用
    如何使用数据库引擎优化顾问优化数据库(转)
    SQLServer数据库慢查询追踪
    怎么获取基金净值数据?(科普)
    解决了一个ssh登录缓慢的问题
    oracle存储过程转达梦8存储过程时踩过的坑2(完结篇)
  • 原文地址:https://www.cnblogs.com/lovemo1314/p/4069600.html
Copyright © 2011-2022 走看看