我已经把函数声明为友元了,怎么还说我不能访问类的私有成员
#include<iostream>
using namespace std;
class a
{
friend ostream& operator<<(ostream& os,const a& s);
private:
int b;
};
ostream& operator<<(ostream& os,const a& s)
{
os<<s.b;
return os;
}
void main()
{}
cs.cpp(11) : error C2248: b : cannot access private member declared in class a
G:\C++\cs.cpp(7) : see declaration of b
Error executing cl.exe.
我用VC++编译你的程序时也出现如下错误:
error C2248: test : cannot access private member declared in class Test
f:\程序\temptest\a.cpp(10) : see declaration of test
Error executing cl.exe.
当我试着运用老的C++标准时,程序完全正常,
说明你的程序没有错,很可能是VC++对新标准
支持的还不够完善。
可以试一试:
#include<iostream.h>
//using namespace std;
class Test
{
Test();
friend ostream & operator<<(ostream&, const Test&);
private:
int test;
};
Test::Test()
{
test = a;
}
ostream & operator<<(ostream &os,const Test &tt)
{
os << "@" << tt.test;
return os;
}
int main()
{
cout << "hello world!"
<< endl;
return 0;
}
我用的Dev C++编译通过了,你试试