C ++ can be used to extract flow stream insertion operator >> and << operator to input and output data types built, may be overloaded operators and extracting stream insertion operator to manipulate objects and other user-defined data types.
We sometimes need to operator overloading function is declared as class friend function, so we can not construct the object and calling the function directly.
/*** inputOver.cpp ***/ #include<iostream> using namespace std; class Distance { private: int feet; int inches; 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; }
operation result:
exbot ubuntu @: ~ / wangqinghe / C ++ / 20190808 $ g ++ inputOver.cpp -o inputOver
exbot @ ubuntu: ~ / wangqinghe / C ++ / 20190808 $ ./inputOver
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
If you reload the program written in the functional form of the members, it will be in the form d1 << cout output data.
/*** memberOver.cpp ***/ #include<iostream> using namespace std; class Distance { private: int feet; int inches; public: Distance() { feet = 0; inches = 0; } Distance(int f,int i) { feet = f; inches = i; } ostream &operator<<(ostream &os) { os << "F: " << feet << " I: " << inches << endl; return os; } }; int main() { Distance d1(20,18); d1 << cout; return 0; }
operation result:
exbot@ubuntu:~/wangqinghe/C++/20190808$ g++ memberOver.cpp -o memberOver
exbot@ubuntu:~/wangqinghe/C++/20190808$ ./memberOver
F: 20 I: 18