大家帮忙看看是怎么回事?怎么回事这样

xero_123 2009-04-30 03:45:48
#include<string>
using namespace std;
class testq
{
private:
string name;
public:
testq(string inn){name=inn;};
friend bool operator == ( testq n1,testq n2);

};

bool operator ==(testq n1,testq n2)
{
if(n1.name==n2.name)
return true;
else
{
return false;
}
}
main()
{

}


这么写出现错误

Compiling...
test.cpp
E:\project\testlist\test.cpp(18) : error C2248: 'name' : cannot access private member declared in class 'testq'
E:\project\testlist\test.cpp(8) : see declaration of 'name'
E:\project\testlist\test.cpp(18) : error C2248: 'name' : cannot access private member declared in class 'testq'
E:\project\testlist\test.cpp(8) : see declaration of 'name'
E:\project\testlist\test.cpp(28) : warning C4508: 'main' : function should return a value; 'void' return type assumed
执行 cl.exe 时出错.

test.obj - 1 error(s), 0 warning(s)


把name改为public后就没有事了,这是怎么回事?
...全文
105 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xero_123 2009-04-30
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 nuoshueihe 的回复:]
因为类的对象不能直接访问内的私有变量,所以改为public好了
常用的解决办法就是设置一个公有函数去访问私有变量,具体见程序中

C/C++ code#include <string>
using namespace std;
class testq
{
private:
string name;
public:
testq(string inn){name=inn;};
friend bool operator == ( testq n1,testq n2);
string getname()
{
return name;
}

};

bo…
[/Quote]


建议好好看一下友元函数和友元类这部分知识。
lpf000 2009-04-30
  • 打赏
  • 举报
回复
没错误啊,我的VC6没问题
nuoshueihe 2009-04-30
  • 打赏
  • 举报
回复
因为类的对象不能直接访问内的私有变量,所以改为public好了
常用的解决办法就是设置一个公有函数去访问私有变量,具体见程序中
#include <string> 
using namespace std;
class testq
{
private:
string name;
public:
testq(string inn){name=inn;};
friend bool operator == ( testq n1,testq n2);
string getname()
{
return name;
}

};

bool operator ==(testq n1,testq n2)
{
if(n1.getname()==n2.getname())
return true;
else
{
return false;
}
}
void main()
{

}
Jinhao 2009-04-30
  • 打赏
  • 举报
回复
VC6 装SP5以上能解决这个问题.
不要再用VC6来学习C++了,会误导

65,211

社区成员

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

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