当我尝试编译这段代码时,我得到:
When I try to compile this code, I get:
52 C:Dev-CppProjektyyystrategyTiles.h invalid use of undefined type `struct tile_tree_apple'
46 C:Dev-CppProjektyyystrategyTiles.h forward declaration of `struct tile_tree_apple'
我的部分代码:
class tile_tree_apple;
class tile_tree : public tile
{
public:
tile onDestroy() {return *new tile_grass;};
tile tick() {if (rand()%20==0) return *new tile_tree_apple;};
void onCreate() {health=rand()%5+4; type=TILET_TREE;};
};
class tile_tree_apple : public tile
{
public:
tile onDestroy() {return *new tile_grass;};
tile tick() {if (rand()%20==0) return *new tile_tree;};
void onCreate() {health=rand()%5+4; type=TILET_TREE_APPLE;};
tile onUse() {return *new tile_tree;};
};
我真的不知道该怎么办,我搜索了解决方案,但找不到任何与我的问题类似的东西...实际上,我有更多与父级tile"相关的课程.之前还可以...
I dont really know what to do, I searched for the solution but I couldn't find anything simmilar to my problem... Actually, I have more classes with parent "tile" and It was ok before...
我决定将所有返回的类型更改为指针以避免内存泄漏,但现在我得到了:
I decided to change all returned types to pointers to avoid memory leaks, but now I got:
27 C:Dev-CppProjektyyystrategyTiles.h ISO C++ forbids declaration of `tile' with no type
27 C:Dev-CppProjektyyystrategyTiles.h expected `;' before "tick"
仅在基类中,其他一切正常... tile 类中返回 *tile 的每个函数都有此错误...
Its only in base class, everything else is ok... Every function in tile class which return *tile has this error...
一些代码:
class tile
{
public:
double health;
tile_type type;
*tile takeDamage(int ammount) {return this;};
*tile onDestroy() {return this;};
*tile onUse() {return this;};
*tile tick() {return this};
virtual void onCreate() {};
};
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!
这篇关于C++ 类前向声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!