注册 登录
编程论坛 C++教室

求教:友元函数无法访问类的私有成员

liwentao8181 发布于 2012-02-04 17:00, 687 次点击
#include <iostream>
using namespace std;
class CVector
{   
    private:
        int x;
        int y;
        int z;
    public:
        friend ostream& operator <<(ostream& out,CVector V);
};
ostream& operator <<(ostream& out,CVector V)
{
    out<<V.x<<endl;//编译时提示这里不能访问CVector的私有成员x。求教
    return out;
}
int main()
{
    return 0;
}
7 回复
#2
liwentao81812012-02-04 17:01
这也编译时出错。大虾们帮一下。
#3
lz10919149992012-02-04 18:46
gcc下编译没问题,你用的是什么编译器?
只有本站会员才能查看附件,请 登录
#4
liwentao81812012-02-05 09:48
哦。版主好。我用的是vc++6.0提示错误。
#5
liwentao81812012-02-05 09:50
回复 3楼 lz1091914999
版主好。我用的是vc++6。0编译的。
Deleting intermediate files and output files for project 'asd - Win32 Debug'.
--------------------Configuration: asd - Win32 Debug--------------------
Compiling...
main.cpp
f:\c++程序\asd\main.cpp(14) : error C2248: 'x' : cannot access private member declared in class 'CVector'
        f:\c++程序\asd\main.cpp(6) : see declaration of 'x'
执行 cl.exe 时出错.

asd.exe - 1 error(s), 0 warning(s)
#6
lz10919149992012-02-05 12:29
我查了一下,这是VC6.0的一个BUG,只要把下面这段代码去掉。
using namespace std;
改为:
using std::cout;
using std::endl;
......
......
把你所有要用到的在std名称空间里的名字依次用using指令声明,而不能一次性打开整个名称空间。
我用VC10编译就没问题:
只有本站会员才能查看附件,请 登录


所以还是早点用新的版本吧,VC6应该淘汰了。
参考:http://
#7
bardon_20092012-02-05 15:48
用VS2010编译通过。
#8
liwentao81812012-02-05 19:55
多谢版主。
1