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

时间:2011-07-12 05:45:34

标签: c++ visual-studio-2010

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

代码:

#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

3 个答案:

答案 0 :(得分:9)

这种情况下的问题似乎是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

答案 1 :(得分:2)

我猜这是来自Sprite.cpp的编译。

Sprite.cpp包含sprite.h,其中包含top.h的game.h。后者包括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
  • 使用它实例化模板

就是这样。可能会有更多,但它们不会是常见的情况,你不应该很快遇到它们。在任何情况下,首先使用前向声明,如果确实不起作用,则包括标题。

答案 2 :(得分:-5)

You need to declare it as a friend in that namespace

class Game
{
    friend class Sprite;

public:
   ...
相关问题