I am learning overloaded operators, I successfully overloaded the <<and >> operators as friend functions creating cout << object and cin >> object. For the next problem I am required to overload the istream operator two ways. I must invoke it as
somephonenumber.operator<<( cout ); or as
somePhoneNumber << cout; I am a little confused on the exact code.
Visual Studio indicates 2 Errors
phonenumber.cpp(25) : error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::ostream' (or there is no acceptable conversion)
phonenumber.h(17): could be 'std::string PhoneNumber::operator <<(const PhoneNumber)'
while trying to match the argument list '(PhoneNumber, std::ostream)'Fig11_05.cpp
fig11_05.cpp(13) : error C2511: 'std::string PhoneNumber::operator <<(const PhoneNumber &)' : overloaded member function not found in 'PhoneNumber'
phonenumber.h(14) : see declaration of 'PhoneNumber'
// Overloaded stream insertion and stream extraction operators
// for class PhoneNumber.
#include <iomanip>
using std::setw;
#include "PhoneNumber.h"
string PhoneNumber::operator<<( const PhoneNumber &right)
{
output << "(" << number.areaCode << ") "
<< number.exchange << "-" << number.line;
return output; // enables cout << a << b << c;
} // end function operator<<
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;
} // end function operator>>
// PhoneNumber class definition
#ifndef PHONENUMBER_H
#define PHONENUMBER_H
#include <iostream>
using std::ostream;
using std::istream;
#include <string>
using std::string;
class PhoneNumber
{
friend istream &operator>>( istream &, PhoneNumber & );
private:
string operator<<( const PhoneNumber );
string areaCode; // 3-digit area code
string exchange; // 3-digit exchange
string line; // 4-digit line
}; // end class PhoneNumber
#endif
// Demonstrating class PhoneNumber's overloaded stream insertion
// and stream extraction operators.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include "PhoneNumber.h"
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: ";
phone << cout << endl;
return 0;
} // end main