简体   繁体   中英

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:

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. 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; , it's still inside the Foo namespace, but your class Bar is outside. Use the unary scope resolution operator to specify that Bar is in the global namespace instead of in Foo :

friend class ::Bar;

You'll also have to either forward declare or define Bar before TestStruct :

class Bar;

namespace Foo {
    ...
}

class Bar {
    ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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