C++ examples for Class:Operator Overload
Overloading the Binary Stream Insertion and Stream Extraction Operators
#include <iostream> #include <string> using namespace std; class PhoneNumber { //from w ww .j a v a 2s . c o m friend ostream &operator<<( ostream &, const PhoneNumber & ) ; friend istream &operator>>( istream &, PhoneNumber & ) ; private: string areaCode; // 3-digit area code string exchange; // 3-digit exchange string line; // 4-digit line }; // end class PhoneNumber #include <iomanip> using namespace std; // overloaded stream insertion operator; cannot be // a member function if we would like to invoke it with // cout << somePhoneNumber; ostream &operator<<( ostream &output, const PhoneNumber &number ) { output << "(" << number.areaCode << ") " << number.exchange << "-" << number.line; return output; // enables cout << a << b << c; } // overloaded stream extraction operator; cannot be // a member function if we would like to invoke it with // cin >> somePhoneNumber; istream &operator>>( istream &input, PhoneNumber &number ) { input.ignore(); // skip ( input >> setw( 3 ) >> number.areaCode; // input area code input.ignore( 2 ); // skip ) and space input >> setw( 3 ) >> number.exchange; // input exchange input.ignore(); // skip dash (-) input >> setw( 4 ) >> number.line; // input line return input; // enables cin >> a >> b >> c; } #include <iostream> using namespace std; int main() { PhoneNumber phone; // create object phone cout << "Enter phone number in the form (123) 456-7890:" << endl; cin >> phone; cout << "The phone number entered was: "; cout << phone << endl; }