【发布时间】:2014-04-29 15:15:30
【问题描述】:
我正在尝试从朋友类访问结构的私有数据成员,如下所示。所有代码都在一个 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 是私有的,因此无法访问。在尝试了不同的事情并在网上搜索后,我最终决定删除命名空间并编译代码。当结构体定义在命名空间中时,为什么我不能从友元类访问结构体的私有数据成员?
【问题讨论】:
-
注意名称的前导下划线;它们大多保留给实现使用——所以你不应该使用它们。
标签: c++ namespaces