请教!请教!重载问题
mhcio 2003-11-30 09:00:04 PhoneNumber1.h:
#ifndef PhoneNumber1H
#define PhoneNumber1H
class PhoneNumber{
friend ostream &operator<<( ostream & , const PhoneNumber &); //就是这里
friend istream &operator>>( istream & , PhoneNumber &);
private:
char areaCode[ 4];
char exchange[ 4];
char line[5];
};
#endif
PhoneNumber1.cpp:
#pragma hdrstop
#include "PhoneNumber1.h"
ostream &operator<<( ostream &output, const PhoneNumber &num)
{
output<<'('<<num.areaCode<<") "<<num.exchange<<'-'<<num.line;
return output;
}
istream &operator>>( istream &input, PhoneNumber &num )
{
input.ignore();
input >> setw(4) >> num.areaCode;
input.ignore(2);
input >> setw(4) >> num.exchange;
input.ignore();
input >> setw(5) >> num.line;
return input;
}
#pragma package(smart_init)
Main.cpp:
#pragma hdrstop
#include <iostream>
using namespace std;
#pragma argsused
int main()
{
PhoneNumber phone;
cout<<"Enter phone number in the form(123) 456-7890:\n";
cin>>phone;
cout<<"The phone number entered was: "<<phone<<endl;
return 0;
}
//------------------------------------------------------------------------
这样编译不过去,说是:Friends must be functions or classes
我如果改成一个文件Main.cpp:
#pragma hdrstop
#include <iostream>
#include <iomanip>
using namespace std;
//---------------------------------------------------------------------------
#pragma argsused
class PhoneNumber{
friend ostream &operator<<( ostream & , const PhoneNumber &);
friend istream &operator>>( istream & , PhoneNumber &);
private:
char areaCode[ 4];
char exchange[ 4];
char line[5];
};
ostream &operator<<( ostream &output, const PhoneNumber &num)
{
output<<'('<<num.areaCode<<") "<<num.exchange<<'-'<<num.line;
return output;
}
istream &operator>>( istream &input, PhoneNumber &num )
{
input.ignore();
input >> setw(4) >> num.areaCode;
input.ignore(2);
input >> setw(4) >> num.exchange;
input.ignore();
input >> setw(5) >> num.line;
return input;
}
int main()
{
PhoneNumber phone;
cout<<"Enter phone number in the form(123) 456-7890:\n";
cin>>phone;
cout<<"The phone number entered was: "<<phone<<endl;
return 0;
}
就正常运行
接口要和实现相分离,合在一起并不是好的方法。
第一种错在那里,我想不出来,请各位帮忙:)