C++ examples for Class:Operator Overload
Overloaded << and >> operators
#include <iostream> using namespace std; class Measure//from w w w. j av a 2 s . c om { private: int feet; float inches; public: Measure() : feet(0), inches(0.0) { } Measure(int ft, float in) : feet(ft), inches(in) { } friend istream& operator >> (istream& s, Measure& d); friend ostream& operator << (ostream& s, Measure& d); }; istream& operator >> (istream& s, Measure& d) //get Measure { cout << "\nEnter feet: "; s >> d.feet; //using cout << "Enter inches: "; s >> d.inches; //overloaded >> operator return s; } ostream& operator << (ostream& s, Measure& d) //display { //Measure s << d.feet << "\'-" << d.inches << '\"'; //using overloaded << operator return s; } int main() { Measure dist1, dist2; Measure dist3(11, 6.25); //define, initialize dist3 cout << "\nEnter two Measure values:"; cin >> dist1 >> dist2; //get values from users cout << "\ndist1 = " << dist1 << "\ndist2 = " << dist2; cout << "\ndist3 = " << dist3 << endl; return 0; }