C++same class as member in class

后端 未结 3 775
轮回少年
轮回少年 2020-12-21 13:53

I have a class that should have a class of the same type as its member.

My declaration is the following:

class clsNode
{
private:
     clsNode m_Moth         


        
相关标签:
3条回答
  • 2020-12-21 14:41

    You can't have a member of the same type inside the class. The compiler tries to calculate the size of the object and sort of "gets into a loop." You can get around that by using indirection. For example, you can store the pointer to the mother node.

    class clsNode
    {
    private:
         clsNode* m_Mother;
    public:
         void setMother(const clsNode &uNode, int index);
    };
    
    0 讨论(0)
  • 2020-12-21 14:42

    The reason is that the type of the member m_Mother has incomplete type at the point it is declared.

    If you think about it. If it would have worked, you would create an object with an object inside with the same type, which in turn always have an object of the same type inside (and so on). The object would in a sense have infinite size.

    One solution is to keep a pointer to the parent class instead.

    class clsNode
    {
    private:
         clsNode* m_Mother;
    public:
         void setMother(clsNode* uNode){ m_Mother=uNode; }
    };
    

    If you would like to have all parents always be alive during the lifetime of their children, you could use a shared pointer instead of a raw pointer.

    class clsNode
    {
    private:
         std::shared_ptr<clsNode> m_Mother;
    public:
         void setMother(std::shared_ptr<clsNode> uNode){ m_Mother=uNode; }
    };
    

    If you go with this solution you would originally create your objects with make_shared

    0 讨论(0)
  • 2020-12-21 14:51

    When you have a member of a class type (directly not a pointer), the instance of your mother class contains physically the contained instance.

    In this case, the compiler can't find the size of the clsNode class as there's a cycle. It should contain a clsNode, which should contain a clsNode, and so forth.

    0 讨论(0)
提交回复
热议问题