C++ 输入/输出运算符重载

  • 输入/输出运算符重载

    C ++能够使用流提取运算符>>和流插入运算符<<输入和输出内置数据类型。流插入和流提取运算符也可以重载,以执行用户定义类型(如对象)的输入和输出。在此,使运算符重载函数成为该类的friend类非常重要,因为它将在不创建对象的情况下被调用。下面的示例说明提取运算符>>和插入运算符<<的方式。
    
    #include <iostream>
    using namespace std;
     
    class Distance {
       private:
          int feet;             // 0 to infinite
          int inches;           // 0 to 12
          
       public:
          // required constructors
          Distance() {
             feet = 0;
             inches = 0;
          }
          Distance(int f, int i) {
             feet = f;
             inches = i;
          }
          friend ostream &operator<<( ostream &output, const Distance &D ) { 
             output << "F : " << D.feet << " I : " << D.inches;
             return output;            
          }
    
          friend istream &operator>>( istream  &input, Distance &D ) { 
             input >> D.feet >> D.inches;
             return input;            
          }
    };
    
    int main() {
       Distance D1(11, 10), D2(5, 11), D3;
    
       cout << "Enter the value of object : " << endl;
       cin >> D3;
       cout << "First Distance : " << D1 << endl;
       cout << "Second Distance :" << D2 << endl;
       cout << "Third Distance :" << D3 << endl;
    
       return 0;
    }
    
    编译并执行上述代码后,将产生以下结果-
    
    $./a.out
    Enter the value of object :
    70
    10
    First Distance : F : 11 I : 10
    Second Distance :F : 5 I : 11
    Third Distance :F : 70 I : 10