且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++ 类前向声明

更新时间:2021-09-03 09:46:58

new T 要编译,T 必须是完整类型.在您的情况下,当您在 tile_tree::tick 的定义中说 new tile_tree_apple 时,tile_tree_apple 是不完整的(它已被前向声明,但是它的定义稍后在您的文件中).尝试将函数的内联定义移动到单独的源文件中,或者至少将它们移动到类定义之后.

In order for new T to compile, T must be a complete type. In your case, when you say new tile_tree_apple inside the definition of tile_tree::tick, tile_tree_apple is incomplete (it has been forward declared, but its definition is later in your file). Try moving the inline definitions of your functions to a separate source file, or at least move them after the class definitions.

类似于:

class A
{
    void f1();
    void f2();
};
class B
{
   void f3();
   void f4();
};

inline void A::f1() {...}
inline void A::f2() {...}
inline void B::f3() {...}
inline void B::f4() {...}

当您以这种方式编写代码时,这些方法中对 A 和 B 的所有引用都保证引用完整类型,因为不再有前向引用!

When you write your code this way, all references to A and B in these methods are guaranteed to refer to complete types, since there are no more forward references!