错误 C2143:'*'之前缺少';'

error C2143 : missing ';' before '*'

本文关键字:错误 C2143      更新时间:2023-10-16

你好,我在网上到处寻找答案,但我找不到任何。

代码:

#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:
   ...