c++中类内部的同一个类的实例



我希望我的类有一个属性,该属性将是同一个类的实例,类似于:

class Person
{
public:
std::string name;
Person nested;
};

这里我的IDE (Visual Studio 2022)说不完整类型是不允许的。在c++中,是否有可能在一个类中拥有同一个类的实例?我该如何实现呢?

Person nested;将有默认值,它是空的Person
所以当你创建Person时,在它里面会自动创建Person,在它里面会创建Person等等

为了避免这种情况,你需要使用指针
class Person
{
public:
std::string name;
Person* nested;
};

来源:https://mrcodehunter.com/incomplete-type-is-not-allowed/

相关内容

最新更新