我有一个叫做Ship()
的类,它看起来像这样
class Ship()
{
public:
vector<Weapon*> Weapon
void AddWeapon(Weapon*)
}
void MyShip::AddWeapon(Weapon*)
{
Weapons.pushback(Weapon)
}
Weapon
类是抽象基类,对于游戏中的每种武器,该基类都必须派生自该基类。其中之一称为Lazer
因此,在我的代码中,我可以执行以下操作:
int main()
{
Ship MyShip;
Lazer MyLazer;
MyShip.AddWeapon(&MyLazer)
}
如何确定
Weapons
中的 vector 指向的对象没有超出范围?我相信答案是在heap
上创建实例,但我不知道。 最佳答案
这样的事情最安全:
#include <memory>
#include <vector>
struct Weapon {
virtual ~Weapon() = default;
};
struct Lazer : Weapon {
};
class Ship
{
public:
void AddWeapon(std::unique_ptr<Weapon> weapon);
private:
std::vector<std::unique_ptr<Weapon>> _weapons;
};
void Ship::AddWeapon(std::unique_ptr<Weapon> weapon)
{
_weapons.push_back(std::move(weapon));
}
// test
using namespace std;
int main(){
auto ship = std::make_unique<Ship>();
ship->AddWeapon(std::make_unique<Lazer>());
return 0;
}
关于c++ - 在 “Heap”上创建实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30361988/