请教各位朋友,问题出在哪???

papaofdoudou
人工智能领域新星创作者
博客专家认证
2009-02-03 09:34:58
我写了一个测试程序,证明一个类的友元函数可以访问该类的私有数据成员,可是结果却显示不能访问该类的私有数据成员,代码如下,请教各位朋友问题出在哪里??
#include <iostream>
using namespace std;




class base
{
friend void display1(base);

public:
friend istream& operator>>(istream& input, base& string);
base(int x=1024)
{
a=x;
}
void display()
{
cout<<a<<endl;
}
private:
int a;
};

void display1(base x) //友元函数的定义
{
cout<<"The color of the car is : "<<x.a<<endl;
}

istream& operator>>(istream& input, base& string)
{
input>>string.a; //访问私有数据成员
cout<<string.a; //访问私有数据成员
return input;

}

void main(void)
{
base mm;
// cin>>mm;
mm.display();
}

编译错误显示:
Compiling...
1.cpp
F:\Program\cha2\1.cpp(33) : error C2248: 'a' : cannot access private member declared in class 'base'
F:\Program\cha2\1.cpp(23) : see declaration of 'a'
F:\Program\cha2\1.cpp(34) : error C2248: 'a' : cannot access private member declared in class 'base'
F:\Program\cha2\1.cpp(23) : see declaration of 'a'
执行 cl.exe 时出错.

cha2.exe - 1 error(s), 0 warning(s)
...全文
60 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
hityct1 2009-02-04
  • 打赏
  • 举报
回复
vc6.0 ,将operator>>的函数体放在base内部就可以了。
deerwin1986 2009-02-03
  • 打赏
  • 举报
回复
按照2楼的方法
或者把
#include <iostream>
using namespace std;
替换为
#include <iostream.h>

这是VC6做友元的2种方法...
没办法 C++标准支持得差啊...
yellowhwb 2009-02-03
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;

class base
{
public:

base(int x=1024)
{
a=x;
}
void display()
{
cout <<a <<endl;
}
private:
int a;
friend void display1(base x) //友元函数的定义
{
cout <<"The color of the car is : " <<x.a <<endl;
}

friend istream& operator>>(istream& input, base& str)
{
input>>str.a; //访问私有数据成员
cout <<str.a; //访问私有数据成员
return input;
}

};


void main(void)
{
base mm;
// cin>>mm;
mm.display();
}

VC6里改成这样
waizqfor 2009-02-03
  • 打赏
  • 举报
回复
[Quote=引用楼主 tugouxp 的帖子:]
我写了一个测试程序,证明一个类的友元函数可以访问该类的私有数据成员,可是结果却显示不能访问该类的私有数据成员,代码如下,请教各位朋友问题出在哪里??
#include <iostream>
using namespace std;


class base
{
friend void display1(base);

public:
friend istream& operator>>(istream& input, base& string);
base(int x=1024)
{
a=x;
}
void display()
{
cout < <a < <endl;
}

[/Quote]
LZ是不是用VC6啊 换个编译器吧
我拿DEV—C++ 输出正常

64,633

社区成员

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

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