C ++与类中的成员相同的类 [英] C++same class as member in class

查看:134
本文介绍了C ++与类中的成员相同的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,应该有一个类与其成员类型相同。



我的声明如下:

  class clsNode 
{
private:
clsNode m_Mother;
public:
void setMother(const clsNode& uNode,int index);
};

C ++告诉我对象显示与成员函数不兼容的类型限定符。 p>

我不知道我在哪里错了。

解决方案



如果你考虑它,如果它的工作,你会创建一个对象其中一个对象在内部具有相同的类型,这反过来总是具有相同类型的对象在内部(等等)。对象在某种意义上将具有无限大小。



一个解决方案是保留一个指向父类的指针。

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

如果你想让所有的父母在孩子的一生中一直活着,你可以使用共享指针的原始指针。

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

如果你使用这个解决方案,你最初用make_shared创建对象


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.

解决方案

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

这篇关于C ++与类中的成员相同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆