简体   繁体   English

访问名称空间中结构的私有数据成员

[英]Accessing the private data members of a struct that is in a namespace

I'm trying to access the private data members of a struct from a friend class as shown below. 我正在尝试从友元类访问结构的私有数据成员,如下所示。 All the code is in a single cpp file: 所有代码都在一个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
}

On compilation, I get an error saying that _testNum in the struct TestStruct is private hence inaccessible. 在编译时,我得到一个错误,说结构TestStruct中的_testNum是私有的,因此无法访问。 After trying different things and searching the web I finally decided to remove the namespace and the code compiles. 在尝试不同的东西并搜索网络后,我最终决定删除命名空间并编译代码。 Why can't I access the private data members of the struct from a friend class when the struct is defined in a namespace? 当在命名空间中定义结构时,为什么我不能从友元类访问结构的私有数据成员?

When saying friend class Bar; friend class Bar; , it's still inside the Foo namespace, but your class Bar is outside. ,它仍然在Foo命名空间内,但你的类Bar在外面。 Use the unary scope resolution operator to specify that Bar is in the global namespace instead of in Foo : 使用一元范围解析运算符指定Bar位于全局命名空间而不是Foo

friend class ::Bar;

You'll also have to either forward declare or define Bar before TestStruct : 您还必须在TestStruct之前转发声明或定义Bar

class Bar;

namespace Foo {
    ...
}

class Bar {
    ...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM