Latest web development tutorials

C ++ operator overloading input and output

C ++ function overloading and operator overloading C ++ function overloading and operator overloading

C ++ can use the stream extraction operator >> and the stream insertion operator << to the input and output built-in data types. You can override the stream extraction and stream insertion operator operator to manipulate objects and other user-defined data types.

Here, it is important, we need to operator overloading function is declared class friend function, so we can not create an object and calling the function directly.

The following example demonstrates how overloaded extraction operator >> and operator << insert.

#include <iostream>
using namespace std;
 
class Distance
{
   private:
      int feet;             // 0 到无穷
      int inches;           // 0 到 12
   public:
      // 所需的构造函数
      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;
}

When the above code is compiled and executed, it produces the following results:

$./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

C ++ function overloading and operator overloading C ++ function overloading and operator overloading