2012-09-15 160 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編譯器正確地告訴你它是一個抽象類。