C++same class as member in class

淺唱寂寞╮ 提交于 2019-11-28 10:00:10

问题


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_Mother;
public:
     void setMother(const clsNode &uNode, int index);
};

C++ tells me "The object shows a type qualifier that is not compatible with the member function.

I don't know where I went wrong.


回答1:


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




回答2:


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);
};



回答3:


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.



来源:https://stackoverflow.com/questions/16756876/csame-class-as-member-in-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!