Overloaded stream insertion study
I'm trying to convert this simple phone number program into a demonstration of using the overloaded stream-insertion operator as a member function, i.e. I'm trying to use
instead of the typical
Can someone point me in the right direction?
Code:
#include <iostream>
#include <iomanip>
using namespace std;
class PhoneNumber {
ostream &operator<<( ostream& ); // defined as a member function
friend istream &operator>>( istream&, PhoneNumber& );
private:
char areaCode[ 4 ]; // 3-digit area code and null
char exchange[ 4 ]; // 3-digit exchange and null
char line[ 5 ]; // 4-digit line and null
ostream &operator<<( ostream &output ) // defined as a member function
{
output << "(" << num.areaCode << ")" << num. exchange << "-" << num.line;
return output; // enables cout << a << b << c;
} // end function operator<<
}; // end class PhoneNumber
istream &operator>>( istream &input, PhoneNumber &num )
{
input.ignore();
input >> setw( 4 ) >> num.areaCode;
input.ignore( 2 ); // skip ( and space
input >> setw( 4 ) >> num.exchange;
input.ignore();
input >> setw( 5 ) >> num.line; // input line
return input;
}
int main()
{
PhoneNumber phone; // create object phone
cout << "Enter phone number in the form (123) 456-7890:\n";
cin >> phone; // operator>>(cin, phone)
cout << "The phone number entered was: ";
//cout << phone << endl; // operator<<( cout, phone );
phone << cout << endl;
phone.operator<<( cout ); // must be defined within the function operator<<
return 0;
} // end main