读书人

将插入器作为类的友元函数的异常

发布时间: 2012-02-24 16:30:39 作者: rapoo

将插入器作为类的友元函数的错误?
#include <iostream>
#include <cstring>
using namespace std;

class phonebook {
// now private
char name[80];
int areacode;
int prefix;
int num;

public:
phonebook(char *n,int a,int p,int nm)
{
strcpy (name ,n);
areacode = a;
prefix = p;
num = nm;
}
friend ostream &operator < <(ostream &stream ,phonebook o);
};

// Display name and phone number.
ostream &operator < <(ostream &stream, phonebook o)
{
stream < < o.name < < " ";
stream < < "( " < < o.areacode < < ") " < < " ";

stream < < o.prefix < < "- " < < o.num < < endl;

return stream ; //must return stream
}

int main()
{
phonebook a( "Ted ", 111 , 555 ,1234);
phonebook b( "Alice ", 312 ,555, 5678 );
phonebook c( "Tom " , 212 ,555, 9991 );

cout < < a < < b < < c;

return 0;
}
_______________________
_______________________
将插入器作为类的友元(friend),为什么不能保证该函数可以访问重载它的类的私有成员呢?

[解决办法]
friend ostream &operator < <(ostream &stream ,const phonebook & o)
{
stream < < o.name < < " ";
stream < < "( " < < o.areacode < < ") " < < " ";
....
}
friend就地实现再说。
[解决办法]
很不幸,这是VC6的一个bug: 当 "using namespace std " 和 friend一同出现时会出问题.
参见: http://support.microsoft.com/?scid=kb%3Ben-us%3B192539&x=11&y=9

解决方法: 用taodm的方法,或者用文中所说方法在class phone的定义之前(也就是紧接using namespace std; 之后)加一个提前声明:

class phonebook;
ostream &operator < <(ostream &stream, phonebook o);

读书人网 >C++

热点推荐