1 c++ methods inheritance class shared-ptr
我的代码有什么问题:
class Game{
private:
mtm::Dimensions dimensions;
std::vector<std::shared_ptr<Character>> board;
};
std::shared_ptr<Character> Game::makeCharacter(CharacterType type, Team team, units_t health,
units_t ammo, units_t range, units_t power) {
std::shared_ptr<Character> out = nullptr;
if (type ==SNIPER)
out=mtm::Sniper(team,health,power,ammo,range);
return out;
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
没有可行的重载 '='
out=mtm::狙击手(团队,健康,力量,弹药,射程);
注意:Sniper继承自抽象类Character。
我该如何解决这个问题?
new构造Sniper对象时需要使用,例如:
out = std::shared_ptr<mtm::Sniper>(new mtm::Sniper(team,health,power,ammo,range));
Run Code Online (Sandbox Code Playgroud)
或者更好,使用std::make_shared()insted:
out = std::make_shared<mtm::Sniper>(team,health,power,ammo,range);
Run Code Online (Sandbox Code Playgroud)
out = mtm::Sniper(...)不起作用,因为std::shared_ptr<Character>期望获得所有权的Character* 指针(或另一个std::shared_ptr<T>共享所有权的指针,其中T可转换为Character)。您正在构造一个本地Sniper对象,然后尝试将其分配给shared_ptr,但Sniper 对象不能隐式转换为Character*指针,但Sniper*指针是(因为Sniper派生自Character)。
而且,在默认情况下std::shared_ptr将delete其拥有的(除非你提供不同的指针deleter),所以你需要使用new(或std::make_shared()),以确保对象的动态内存可以构建delete“d正常。这意味着new它。