33,311
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
using std::istream;
#include <iomanip>
using std::setw;
class PhoneNumber
{
friend ostream &operator <<( ostream&, const PhoneNumber & );
friend istream &operator >>( istream&, const PhoneNumber & );
private:
char areaCode[ 4 ]; //3-digit area code and null
char exchange[ 4 ]; //3-digit exchange and null
char line[ 5 ]; //4-dighit line and null
};
//Overloaded stram-insertion operator( cannot be
//a member function if we would like to invoke it with
//cout << somePhoneNumber; )
ostream &operator <<( ostream &output, const PhoneNumber &num )
{
output << "(" << num.areaCode << ")"
<< num.exchange << "-" << num.line;
return output; //enables cout << a << b << c;
}
istream &operator >>( istream &input, const PhoneNumber &num )
{
input.ignore(); //skip (
input >> setw( 4 ) >> num.areaCode; //这里报错
input.ignore( 2 ); //skip )
input >> setw( 4 ) >> num.exchange; //这里报错
input.ignore(); //skip dash (-)
input >> setw( 5 ) >> num.line; //这里报错
return input; //enables cin >> a >> b >> c;
}
int main()
{
PhoneNumber phone; //create object phone
cout << "Enter phone number in the form (123) 456-7890: \n";
//cin >> phone invokes operator >> function by
//issuing the call operator >>( cin, phone ).
cin >> phone;
//cout << phone invokes operator << function by
//issuing the call operator <<( cout, phone ).
cout << "The phone number entered was: " << phone << endl;
system("pause");
return 0;
}