重载operator<<的迷惑,关于cannot access private member declared in class

来源:互联网 发布:小数据分析 编辑:程序博客网 时间:2024/05/16 09:12
今天写C++时,用到了友员重载 << ,但编译是提示cannot access private member declared in class
到网上找了一下解决方案,我发现这个帖子很不错,拿来共享.
原文地址:http://blog.163.com/hotman_x.vip/blog/static/48950133200810365331315/

这个本是一个初学者问我的一个简单问题,不过最终答案却有点复杂,俺也是“猛然想起”,自己也不知正误,引用于此,并将回复问答抄下,备忘吧。

引用

mGc|TonY.Joe.S重载operator<<的迷惑

#include <iostream>
using namespace std;


class List
{
public:
 friend ostream & operator << (ostream &out,const List &l);
 friend void showdata(List &l);

 List(){data=10;}
 void show(){cout<<data<<endl;}
 
private:
 int data;
 //......
};

void showdata(List &l)
{
 cout<<l.data <<endl;    
}

ostream & operator <<(ostream &out,List &l)
{
 //out<<l.data<<endl;     

 return out;
}

int main()
{
 List l;
 l.show ();
 cout<<l<<endl;
 showdata(l);
 return 0;
}

写这段程序的时候真是很迷惑,你看,operator <<( )和showdata()都是类List的友元函数

为什么showdata()直接访问l的私有数据data没有问题,而operator <<( )访问就要报出下面的错误呢?(编译产生)


C:/Documents and Settings/Administrator/桌面/pailie.cpp(25) : error C2248: 'data' : cannot access private member declared in class 'List'
        C:/Documents and Settings/Administrator/桌面/pailie.cpp(14) : see declaration of 'data'

 

 

以下是问答:

代码之诗:因为你定义 operator << 的时候,参数类型 List 少写一个 const ,所以它的 function signature 发生了变化,编译器认为它与你前面声明的友元不是同一个操作符。

 

mGc|TonY.J

谢谢你,但是我那样改以后在VC++6.0上还是不行,同样的错误.

不过也总算找到错误所在了,只是看起来也很滑稽:

就是把

#include <iostream>
using namespace std;

改成

#include <iostream.h>

。。

解决办法是找到了,不过却更糊涂了!

 

代码之诗:你这个做法不对。这里改后又报别的什么错?

 

代码之诗:哦,我猜……你的VC6没有打上SP4补丁吧?那么它不支持 Kornig 查找。不是你代码的问题,而是编译器太老了。如果不打补丁的话,除非你把这个 operator << 放到 std 命名空间里去。这显然更不妥,还是去打补丁吧。如果可能,换用新的 VC 更好。