c++定义一个Node类,它有一个私有变量Node(一个用于*的Node)

c++ defining a Node class, which has a private variable of Node (a Node for use in a*)

本文关键字:Node 一个 变量 用于 定义 c++ 有一个      更新时间:2023-10-16

我是c++的新手,我正在尝试定义一个Node类,它包含关于另一个节点的信息,在这种情况下,节点将是父节点,因此我可以使用a *搜索跟踪最优路线。

到目前为止,我已经尝试了(node.h文件):

class node{
    private:
    int xCoord;
    int yCoord;
    int value;
    int hueristicCost;
    int pathCost;
    class node parent;
    public:
    node(int xC, int yC, int value);
    int getXPos();
    int getYPos();
    int getValue();

};

但是这会抛出编译错误:

node.h:10:13: error: field ‘parent’ has incomplete type

我可能错过了一些愚蠢的明显,但我该如何去完成这个?

成员必须是完整类型(正如错误消息遗忘已经告诉您的那样)。这意味着你不能有前向声明的成员。

注意,您已经可以在节点类中使用node(作为完整类型)。

然而,定义node类型的成员仍然是不可能的,因为这会导致无限递归。因此,如果你有一个树状模型,你可能需要一个node*。还要注意,class Foo* member;确实是可能的。如果你真的不能避免前向声明,这是通常的解决方案。

不能在类中声明类的对象。

可能的重复:为什么不能在同一个类中声明一个类的对象?

相反,您可以像其他人提到的那样定义指针:

node* parent

class node parent;

应:

node parent;

或者说:

node* parent;
相关文章: