Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

c++ - C++same class as member in class

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...