C++ 错误 : field has incomplete type - declaring it's own class object

标签 c++

<分区>

我是 C++ 编程新手。这是我的代码:

#ifndef NODE_H
#define NODE_H    

class Node
{
    public:
        Node();
        Node(int);
        virtual ~Node();
        Node(const Node& other);

        int getValue() { return value; }
        void setValue(int val) { value = val; }
        Node getPrev() { return prev; }
        void setPrev(Node val) { prev = val; }
        Node getNext() { return next; }
        void setNext(Node val) { next = val; }

    private:
        int value; //!< Member variable "value"
        Node prev; //!< Member variable "prev"
        Node next; //!< Member variable "next"
};

#endif // NODE_H

它说:

error field 'prev' has incomplete type
error field 'next' has incomplete type

如果我使用指针/引用,程序运行良好。为什么会存在这种机制?没有指针/引用怎么办? 感谢您的回复。

最佳答案

直到那个右大括号,类才被完全定义。在此之前,您不能定义类的对象。一个主要原因是对象的大小尚不清楚,因此编译器不知道为成员变量分配多少内存。

当您使用类的指针或引用时,编译器将知道指针或引用占用了多少内存,因为它与实际类的大小无关。

关于C++ 错误 : field has incomplete type - declaring it's own class object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40886258/

相关文章:

c++ - 通过指针访问私有(private)虚拟成员函数

c++ - 如何在C++中chartdirector的XY图表中的自定义位置添加标签?

c++ - 如何构造像 C# WinForms 这样的 C++ Windows API 程序

c++ - Project Euler #23,在程序中找不到问题

c++ - 平台游戏(如马里奥兄弟)的碰撞不起作用

c++ - Cmake 无法识别 MSVC 编译器

c++ - 清理遗留代码 "header spaghetti"

c++ - 为什么 std::adressof() 在无效输入时表现如此?

c++ - 什么是 "Microsoft C++ exception"?

c++ - 在 C++ 源代码中使用 Unicode