我试图从朋友类访问结构的私有数据成员,如下所示。所有代码都在一个cpp文件中:
namespace Foo
{
struct TestStruct
{
friend class Bar;
private:
int _testNum;
};
}
class Bar
{
public:
Bar();
private:
Foo::TestStruct _testStructObj;
};
Bar::Bar()
{
_testStructObj._testNum = 10; //Cannot modify _testNum because it is private
}
在编译时,我收到错误,说结构TestStruct中的_testNum是私有的,因此无法访问。在尝试不同的东西并搜索网络后,我最终决定删除命名空间并编译代码。当在命名空间中定义结构时,为什么我不能从友元类访问结构的私有数据成员?
答案 0 :(得分:3)
说friend class Bar;
时,它仍在Foo
命名空间内,但您的班级Bar
在外面。使用一元范围解析运算符指定Bar
位于全局命名空间而不是Foo
中:
friend class ::Bar;
您还必须在Bar
之前转发声明或定义TestStruct
:
class Bar;
namespace Foo {
...
}
class Bar {
...
};