C++ Access private member of nested class

前端 未结 3 1623
再見小時候
再見小時候 2021-01-19 10:21

The title might be a bit misleading. I have the following problem: I have a tree consisting of leaves and internal nodes. The user should be able to store any information in

相关标签:
3条回答
  • 2021-01-19 11:05

    You can declare class Tree a friend to UserElement<>, which would allow Tree to access all members of UserElement<>.

    0 讨论(0)
  • 2021-01-19 11:12

    You may do

    class Outer {
       private: // maybe protected:
       class Inner {
          public:
          ....
       };
    };
    

    or

    class Outer {
       public:
       class Inner {
          friend class Outer;
          private:
          ....
       };
    };
    
    0 讨论(0)
  • 2021-01-19 11:20

    Technically, that's a nested class (declared within another class), not a subclass (which inherits from its superclass).

    You can allow the Tree class to access its privates by making it a friend:

    class UserElement {
        friend class Tree;
        // ...
    };
    

    or, for better encapsulation, you could restrict access only to the member function(s) that need it, although it gets a bit messy due to the need to declare things in the right order:

    class Tree {
    public:
        // Declare this so we can declare the function
        template <typename T> class UserElement;
    
        // Declare this before defining `UserElement` so we can use it
        // in the friend declaration
        template <typename T>
        void doSomethingWithTheTree(list<UserElement<T>> elements) {
            elements.front().leaf;
        }
    
        template <typename T>
        class UserElement {
            // Finally, we can declare it a friend.
            friend void Tree::doSomethingWithTheTree<T>(list<UserElement<T>>);
            // ...
        };
    };
    
    0 讨论(0)
提交回复
热议问题