c++ - 在 C++ 中如何创建一个可以将自身保存为变量的类?

标签 c++ class oop forward-declaration incomplete-type

<分区>

我是 C++ 的新手,我的大部分作品都是用 Python 编写的。

在 Python 中,如果我想创建一个类来保存有关人类的信息,我可以编写一个可以将其“父”作为其变量之一保存的类。在 Python 中,我会大致这样做:

class Human:

    def __init__(self, name):
        self.name = name


first = Human("first")
second = Human("second")

second.parent = first

second.parent = first 表示人类 second 的父级是人类 first

在 C++ 中,我尝试实现类似的东西:

class Human {

    public:
        Human parent;

};

int main() {
    Human first = Human();
    Human second = Human();

    second.parent = first;
}

此示例带有一个错误,即 field has incomplete type: Human。我明白了,因为它说我的人类对象中不能有人类,因为人类是什么还没有完整的定义。当我搜索相关帖子时,我不断地遇到使用前向声明和指针的解决方案,但我一直无法使其正常工作。

我非常感谢任何帮助使 c++ 示例按照我想要的方式运行。

谢谢。

最佳答案

例如通过使用指针:

struct Human
{
    Human* parent;  // The symbol Human is declared, it's okay to use pointers to incomplete structures
};

int main()
{
    Human first = Human();
    Human second = Human();

    second.parent = &first;  // The & operator is the address-of operator, &first returns a pointer to first
}

您也可以使用引用,但使用和初始化这些引用可能会有点困难。

关于c++ - 在 C++ 中如何创建一个可以将自身保存为变量的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52164627/

相关文章:

C++ 双重声明/定义?

c++ - 线程在 while 循环中间随机停止

javascript - 何时在 React 中使用基于类的组件

javascript - 自定义字符串类

Javascript 新函数对象与函数实例化

c++ - 什么是 string array[] = "";意思是为什么它有效?

c++ - Ide 发布错误,但程序运行

python - 当类也在不同的模块中时从另一个模块访问对象?

c++ - 没有友元函数的两个类的私有(private)操作

javascript - 将原型(prototype)方法放入 js 字典中