2014-11-24 66 views
2

我有一個類Player,我想有一個成員primaryWeapon可以設置爲從類Gun派生任何數量的類。只是想知道如何去做這件事。我試圖設置它,但我不知道該從哪裏去。C++ - 基類作爲屬性

class Player : public Character { 
    public: 
     Player(); 
     ~Player(); 

     Gun primaryWeapon; 

     void update(); 
     void move(float horizontal, float vertical); 
     void fire(); 
}; 
+1

你需要多態的指針或引用。 'gun * primaryWeapon;'(或者,更好的辦法是使用一個像std :: shared_ptr 或者std :: unique_ptr 這樣的智能指針。) – cdhowie 2014-11-24 21:33:54

+0

試過了。但是,在執行primaryWeapon = new DevPistol()時,它會拋出一個錯誤「No viable overloaded'='」 – 2014-11-24 21:38:16

+3

當出現此錯誤時,'primaryWeapon'的類型是什麼?例如,如果它是'std :: unique_ptr',那麼你需要執行'primaryWeapon.reset(new DevPistol())'。 – sfjac 2014-11-24 21:39:46

回答

2

當用C使用多態行爲++,需要經由任一個的提及或引用多態對象指針。你的例子是按值存儲Gun對象,這將導致對象從任何派生類型「切片」到基類型。

無論您使用參考,原始指針,shared_ptrunique_ptr取決於您的程序的總體設計,但其中的一個將會訣竅。

0

你可以使用一個指向Gun的指針來使用primaryWeapon;

boost::shared_pt<Gun> shrdPrimaryWeapon; 

然後,定義在槍多態函數(像getWeaponAmmoForExample),並用使用它:

shrdPrimaryWeapon->getWeaponAmmoForExample(); 
1

如果你想要多態行爲,你需要primaryWeapon作爲引用,指針或智能指針。一個參考可以防止玩家更改他們的primaryWeapon,這似乎是一個恥辱。所以這留下(聰明的)指針。如果你的玩家擁有他們的槍,我推薦unique_ptr

#include <memory> 

class Gun { 
public: 
    virtual ~Gun(){} 
}; 

class Glock : public Gun {}; 

class Player { 
public: 
    void setPrimaryWeapon(std::unique_ptr<Gun> weapon) { 
    primaryWeapon = std::move(weapon); 
    } 
private: 
    std::unique_ptr<Gun> primaryWeapon;  
}; 

int main() { 
    Player player; 
    player.setPrimaryWeapon(std::make_unique<Glock>()); 
}