c ++ - 基类作为属性

时间:2014-11-24 21:32:06

标签: c++ inheritance

我有一个类Player,我希望有一个成员primaryWeapon,可以设置为从类Gun派生的任意数量的类。只是想知道如何去做这件事。我已经尝试过这样设置,但我不确定从这里开始。

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

        Gun primaryWeapon;

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

3 个答案:

答案 0 :(得分:2)

在C ++中使用多态行为时,需要通过引用或指针引用多态对象。您的示例是按值存储Gun对象,这将导致对象从任何派生类型“切片”到基本类型。

您是否使用引用,原始指针shared_ptrunique_ptr取决于程序的整体设计,但其中一个可以解决问题。

答案 1 :(得分: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>());
}

答案 2 :(得分:0)

你可以使用枪指针来获得primaryWeapon;

boost::shared_pt<Gun> shrdPrimaryWeapon;

然后在Gun中定义多态函数(如getWeaponAmmoForExample)并将其用于:

shrdPrimaryWeapon->getWeaponAmmoForExample();
相关问题