我有一个很小的问题。为什么此代码引发以下错误?
字段下一个具有不完整的类型。
我正在声明一个类,它有一个属性
#ifndef NODE_H
#define NODE_H
class Node
{
public:
int d;
Node(int d){
this->d = d;
}
Node next = 0;
};
#endif // NODE_H
但!!!如果我更改为指针有效:
Node *next;
很有趣,因为这来自破解编码采访的书。
有人可以对我有所了解吗?(一个很可能让我感到羞耻:D)
提前致谢
我做了功课,但在这里或这里都找不到解决方案
您正在声明一个类型 Node
的类,但该声明在到达右大括号和分号之前不完整。
class Foo
{
}; // Class declaration is complete now
但是,以下内容不起作用,请参阅代码注释。
class Node
{
public:
int d;
Node(int d){
this->d = d;
}
// This is a instance of a class and as such the compiler needs to
// know the full definition of the class. HOWEVER, this is the class
// that's being defined (i.e., it isn't fully defined yet!)
Node next = 0; // Assigning 0 here doesn't make any sense
};
指针不需要完整的但!!!如果我更改为指针工作
类型(即不需要完整的定义),因此可以在定义Node
类时使用。
这不是我得到的错误,那只是智能感知错误。
但是,Node
尚未完全定义,因此编译器不知道它是哪种对象,或者它占用了多少内存。
无论如何,我不认为这是问题所在。 在 Node
类本身中声明 Node
对象将创建递归依赖关系,同样,编译器将无法解析Node
需要多少内存。
由于指针只是一个内存地址并且具有固定的大小,因此编译器很高兴并且可以声明它。