2012-09-15 161 views
1

(我很新的C++,所以希望这只是一个新手的错误)C++ - 无法实例化抽象类

我有我的代码,在那里我有一个类“玩家”的问题,需要一些属性,其中我尝试给它虽然使用抽象类的这样:

//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) 
{ 
} 

然而我不断收到合作mpilation错误: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; 
}; 
+6

''玩家'必须覆盖它所派生类的所有纯虚函数**。 –

回答

0

一个抽象类是抽象的 - 即的东西是没有定义,而只是宣布。

您需要定义所有这些方法。由于我没有这些类的声明,我不能告诉你你错过了什么方法。

0

在C++中,除非它被专门编写的函数不是虚:

virtual void move(Uint32 dTime); 

pure virtual function的定义如下:

virtual void move(Uint32 dTime) = 0; 

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

+0

我完全忘了添加纯虚函数。他们已经被编辑到现在的原始文章。 – user1673234

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来捕获这样的错误。

0

当然,这是由于错过了一个纯虚函数的覆盖 - 也许只是一个微妙的标记差异。

我希望编译器会告诉你哪个功能仍然没有覆盖,像(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' 

如果你的编译器没有报告这一点,你可以通过删除继承的接口之一查询一个。

+0

不幸的是,它告诉我这样的事情:( – user1673234

+0

@ user1673234你正在使用哪个编译器和版本 –

3

你的问题是在这里:

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编译器正确地告诉你它是一个抽象类。