错误 C2143:'*'之前缺少';'
error C2143 : missing ';' before '*'
你好,我在网上到处寻找答案,但我找不到任何。
代码:#ifndef GAME_H
#define GAME_H
#include "drawEngine.h"
#include "sprite.h"
#include <iostream>
using namespace std;
class Game
{
public:
bool run(void);
protected:
bool getinput(char *c);
void timerUpdate(void);
private:
Sprite* player; // this gives me C2143
double frameCount;
double startTime;
double lastTime;
int posx;
//int posy;
DrawEngine drawArea;
};
#endif
如何解决这个问题?
sprite.h
#ifndef GAME_H
#define GAME_H
#include "drawEngine.h"
#include "game.h"
enum
{
SPRITE_CLASSID,
};
struct vector
{
float x;
float y;
};
class Sprite
{
public:
Sprite(DrawEngine *de, int s_index, float x = 1, float y = 1, int i_lives = 1);
~Sprite();
vector getPosition(void);
float getX(void);
float getY(void);
virtual void addLives(int num = 1);
int getLives(void);
bool isAlive(void);
virtual bool move(float x, float y);
protected:
DrawEngine *drawArea;
vector pos;
int spriteIndex;
int numLives;
int classID;
vector facingDirection;
void draw(float x, float y);
void erase(float x, float y);
private:
};
#endif
在这种情况下,问题似乎是Sprite
未被识别为类型。仔细一看,问题在于您定义了:
#ifndef GAME_H
#define GAME_H
//...
#endif
在两个文件中。你可以在。cpp文件(或Game.h文件)中这样做。第一个代码片段),你也可以在Sprite.h文件中这样做。问题是,当编译器转到Sprite.h时,GAME_H已经被定义,因此,由于#ifndef
例程,它不再编译Sprite.h文件。
修改Sprite.h文件:
#ifndef SPRITE_H
#define SPRITE_H
//...
#endif
我猜这是从Sprite.cpp的编译。
Sprite.cpp包含sprite.h,其中顶部包含game.h。后一个include又包含了sprite.h,由于它的包含保护或pragma,它什么也不做。这意味着,在这一点上,没有已知的类称为sprite -在这个编译中,它在它下面。
结果代码(预处理后,编译前)如下所示:class Game { Sprite *... };
class Sprite { ... };
Sprite::func() {};
本质上,你不能轻易地修复这个问题。您需要使其中一个头不依赖于首先包含的另一个头。你可以这样做,每次你不需要类的内容时,转发声明它,而不是包含它。
class Game;
class Sprite {...};
和
class Sprite;
class Game { Sprite *...};
所以如果你这样做,然后编译sprite。cpp,预处理后的输出将看起来像
class Sprite;
class Game { Sprite *... };
class Sprite { ... };
Sprite::func() {};
可以工作。编译器不需要在声明指向Sprite的指针时确切地知道它是什么。事实上,唯一需要完整声明的情况是:
- 使用类 的成员
- 从 类继承
- 在类 上使用sizeof
- 你用它实例化一个模板
就是这样。可能还有更多的例子,但它们不会是常见的情况,你不应该那么快就遇到它们。在任何情况下,首先使用前向声明,如果这确实不起作用,然后包括头。
您需要在该命名空间中将其声明为友元。
class Game
{
friend class Sprite;
public:
...
相关文章:
- 为什么我会收到错误 C2143 语法错误:缺少"*"之前的';'?
- 错误 C2143:语法错误:':'之前缺少','
- 编译错误 C2143:语法错误:'<'之前缺少';'
- 错误 C2143:语法错误:'<' C++之前缺少';'
- 错误 C2143:语法错误:在"*"之前缺少"{"
- 请求分号时出现令人困惑的错误(错误 C2143)
- 两个语法错误:错误 C2143 语法错误:'*'之前缺少';'
- 可变参数模板 - 错误 C2143:语法错误:'...'之前缺少','
- 错误 C2143:语法错误:':'之前缺少';'
- CS106b 库矢量.cpp错误 C2143:语法错误:'<'之前缺少';'
- 模板类引发错误 C2143:语法错误:在"<"之前缺少";"
- C++ 结构 - 错误 1 错误 C2143:语法错误:缺少'*'之前的';'
- 错误 C4430:AND 错误 C2143:语法错误:'*'之前缺少';'
- 错误 C2143:语法错误:声明指针时'*'之前缺少';'
- afxtempl.h 错误 12 错误 C2143:语法错误:缺少'}'之前的';'
- C++:错误 C2143:语法错误:'<'之前缺少';'
- 错误 C2143:语法错误:命名空间之前缺少";"
- 错误 C2143:语法错误:'if'之前缺少';'
- 错误 C2143:语法错误:在"__stdcall"之前缺少";"
- 在函数定义中指定参数默认值会导致错误 C2143:语法错误:'='之前缺少')'