問題描述
當我嘗試編譯這段代碼時,我得到:
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模板網!