C ++ - 无法实例化抽象类

时间:2012-09-15 11:16:35

标签: c++ visual-c++ abstract-class virtual-functions

(我对C ++很陌生,所以希望这只是一个新手的错误)

我在我的代码中遇到问题,我有一个类“Player”需要许多属性,我试图通过使用抽象类来实现它:

//player.h

class Player : public IUpdate, public IPositionable, public IMoveable, public IDrawable
{
public:
    Player(void);
    SDL_Rect get_position();
    void move(Uint32 dTime);
    void update(Uint32 dTime);
    void show(SDL_Surface* destination);
    ~Player(void);
private:
    SDL_Surface texture;
    int x, y;
};

我正在重写纯虚函数:

//Player.cpp
Player::Player(void)
{
}

SDL_Rect Player::get_position()
{
    SDL_Rect rect;
    rect.h = 0;
    return rect;
}

void Player::move(Uint32 dTime)
{

}

void Player::update(Uint32 dTime)
{
    move(dTime);
}

void Player::show(SDL_Surface* destination)
{
    apply_surface(x, y, &texture, destination, NULL);
}

Player::~Player(void)
{
}

但是我一直收到编译错误:C2259: 'Player' : cannot instantiate abstract class

据我所知,纯粹的虚拟函数应该被覆盖,我的谷歌搜索告诉我,这些函数会使Player非抽象,但Player似乎仍然是抽象的。

编辑: 纯虚函数:

class IPositionable
{
public:
    virtual SDL_Rect get_position() = 0;
private:
    int posX, posY;
};

class IUpdate
{
public:
    virtual void update (Uint32 dTime) = 0;
};

class IMoveable
{
public:
    int velX, velY;
    virtual void move(Uint32 dTime) = 0;
};

class IDrawable
{
public:
    virtual void show() = 0;
private:
    SDL_Surface texture;
};

class IHitbox
{
    virtual void check_collsion() = 0;
};

class IAnimated
{
    virtual void next_frame() = 0;
    int state, frame;
    int rows, columns;
};

5 个答案:

答案 0 :(得分:4)

你的问题在这里:

class IDrawable
{
public:
    virtual void show() = 0;
};

void Player::show(SDL_Surface* destination)
{
    apply_surface(x, y, &texture, destination, NULL);
}

请注意,Player::show(SDL_Surface* destination)不会覆盖纯虚方法IDrawable::show() 为了覆盖该方法,您需要在派生类中使用完全相同的函数签名(仅允许共变型返回类型
你现在拥有的是派生类中名为show()的方法, hides 基类中名为show()的方法,它不会覆盖它。既然你没有为你的类的所有纯虚函数提供定义Player编译器正确告诉你它是一个抽象类。

答案 1 :(得分:1)

有可能不是覆盖其中一个基础的纯虚函数,而是声明并定义了一个具有微妙不同签名的函数,如下所示:

struct base {
    virtual void foo(double d) = 0;
};

struct derived: base {
    // does not override base::foo; possible subtle error
    void foo(int i);
}

您可能希望通过查看代码来仔细检查代码。如果您使用的是C ++ 11,则可以标记函数override以捕获此类错误。

答案 2 :(得分:0)

抽象类是抽象的 - 即某些东西未定义但只是声明。

您需要定义所有这些方法。由于我没有这些课程的声明,我不能告诉你你缺少什么方法。

答案 3 :(得分:0)

在C ++中,除非专门编写函数,否则函数不是虚函数:

virtual void move(Uint32 dTime);

pure virtual function的定义如下:

virtual void move(Uint32 dTime) = 0;

你继承的“接口”(注意这是multiple inheritance .. C ++与类没有不同的接口)有你没有实现的纯虚函数,从而使你的类抽象化。

答案 4 :(得分:0)

肯定是因为错过了纯虚函数的覆盖 - 可能只是一个微妙的sigature差异。

我希望编译器会告诉你哪个函数仍然没有被覆盖,比如(vc9):

C2259: 'Player' : cannot instantiate abstract class
due to following members:
'void IUpdate::update(void)' : is abstract
virtualclass.cpp(3) : see declaration of 'IUpdate::update'

如果您的编译器没有报告此情况,您可以逐个删除继承的接口进行检查。