首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2012-02-24 
将插入器作为类的友元函数的错误?#include iostream#include cstringusingnamespacestdclassphoneboo

将插入器作为类的友元函数的错误?
#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);

热点排行