你如何创建一个 class 可以将自己作为 C++ 中的变量?
How do you create a class which can hold itself as a variable in c++?
我是 c++ 的新手,我的大部分作品都是在 Python 中编写的。
在 Python 中,如果我想创建一个 class 来保存关于人类的信息,我可以写一个 class 来保存它的 'parent' 作为一个它的变量。在 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
}
您也可以使用引用,但使用和初始化这些引用可能会有点困难。
你能做的是
class Human {
public:
Human * parent = nullptr;
};
它应该是一个指针,最好初始化。
你可以通过在相同类型的 class 中保留一个指针 属性 来实现。
喜欢
class Human {
...
...
public : Human* parent;
...
...
}
并可用作:
int main()
{
Human* h1 = new Human;
Human* h2 = new Human;
h2->parent = h1;
...
...
delete h1;
delete h2;
}
指针在这里很有意义,指针将内存地址保存到您正在引用的任何内容,而不会将实际数据存储在其中 class。
E.G
class Human {
public:
Human * parent;
};
你的父级现在实际上存储为一个内存地址,但是 *parent 它被用作一个对象,例如你可以这样做:
myHuman.parent->parent(-> 意思是取消引用然后是“.”)
我是 c++ 的新手,我的大部分作品都是在 Python 中编写的。
在 Python 中,如果我想创建一个 class 来保存关于人类的信息,我可以写一个 class 来保存它的 'parent' 作为一个它的变量。在 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
}
您也可以使用引用,但使用和初始化这些引用可能会有点困难。
你能做的是
class Human {
public:
Human * parent = nullptr;
};
它应该是一个指针,最好初始化。
你可以通过在相同类型的 class 中保留一个指针 属性 来实现。 喜欢
class Human {
...
...
public : Human* parent;
...
...
}
并可用作:
int main()
{
Human* h1 = new Human;
Human* h2 = new Human;
h2->parent = h1;
...
...
delete h1;
delete h2;
}
指针在这里很有意义,指针将内存地址保存到您正在引用的任何内容,而不会将实际数据存储在其中 class。
E.G
class Human {
public:
Human * parent;
};
你的父级现在实际上存储为一个内存地址,但是 *parent 它被用作一个对象,例如你可以这样做: myHuman.parent->parent(-> 意思是取消引用然后是“.”)