我对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
}
您也可以使用引用,但是使用它们和初始化它们可能会有些困难。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句