我写的友元函数为什么不能访问私有成员,请指出错误,谢谢

freezhATsis 2009-09-26 09:42:02
为什么写成friends函数还是不能访问private成员

请指出我写的程序的错误,谢谢!




////////////////////////////////////////
#include<iostream>
using namespace std;

class test
{
private:
int x,y;
public:
test(int i,int j){
x = i;
y = j;
}
~test(){}
friend ostream& operator<<(ostream& stream,test ob);
};

ostream& operator<<(ostream& stream,test ob){
stream<<ob.x<<","<<ob.y<<endl;
return stream;
}

int main()
{
test a(5,6),b(20,23);
cout<<a<<endl<<b<<endl;

return 0;
}

///////////////////////////////
错误为:

ostream.cpp(24) : error C2248: 'x' : cannot access private member declared in class 'test'
ostream.cpp(13) : see declaration of 'x'
ostream.cpp(24) : error C2248: 'y' : cannot access private member declared in class 'test'
ostream.cpp(13) : see declaration of 'y'
ostream.cpp(31) : error C2593: 'operator <<' is ambiguous



...全文
145 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
freezhATsis 2009-09-26
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 zgjxwl 的回复:]
把友元函数的实现写在类里。。。这是VC6的bug

具体其他解决办法。。。可以看我的blog里有篇文章。
[/Quote]

你blog里的方法很管用,谢谢!
mstlq 2009-09-26
  • 打赏
  • 举报
回复
连友元我都不想用……
mstlq 2009-09-26
  • 打赏
  • 举报
回复
vc6的bug……
下面是一种绕过bug的方法……


#include<iostream>
using namespace std;

class test
{
private:
int x,y;
public:
test(int i,int j){
x = i;
y = j;
}
~test(){}
void print(ostream& stream);
};
void test::print(ostream& stream)
{
stream<<x<<","<<y<<endl;
};
ostream& operator<<(ostream& stream,test ob){
ob.print(stream);
return stream;
}

int main()
{
test a(5,6),b(20,23);
cout<<a<<endl<<b<<endl;
return 0;
}
zgjxwl 2009-09-26
  • 打赏
  • 举报
回复
把友元函数的实现写在类里。。。这是VC6的bug

具体其他解决办法。。。可以看我的blog里有篇文章。
wanjingwei 2009-09-26
  • 打赏
  • 举报
回复
vc6的bug

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧