C++same class as member in class

后端 未结 3 774
轮回少年
轮回少年 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: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 m_Mother;
    public:
         void setMother(std::shared_ptr uNode){ m_Mother=uNode; }
    };
    

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

提交回复
热议问题