没有可行的超载'='用于shared_ptr

no viable overloaded '=' for shared_ptr

本文关键字:用于 shared ptr 超载      更新时间:2023-10-16

我的代码有什么问题:

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;
}

我收到以下错误:

没有可行的重载"=" out=mtm::狙击手(团队,生命值,力量,弹药,射程(;

注意:Sniper继承自抽象类Character

我该如何解决这个问题?

构造Sniper对象时需要使用new,例如:

out = std::shared_ptr<mtm::Sniper>(new mtm::Sniper(team,health,power,ammo,range));

或者更好的是,改用std::make_shared()

out = std::make_shared<mtm::Sniper>(team,health,power,ammo,range);

out = mtm::Sniper(...)不起作用,因为std::shared_ptr<Character>期望一个Character*指针来获取所有权(或与之共享所有权的其他std::shared_ptr<T>,其中T可转换为Character(。 您正在构造一个本地Sniper对象,然后尝试将其分配给shared_ptr,但是Sniper对象不能隐式转换为Character*指针,而是Sniper*指针(因为Sniper派生自Character(。

而且,默认情况下,std::shared_ptrdelete它拥有的指针(除非您提供不同的deleter(,因此您需要使用new(或std::make_shared()(来确保对象是在可以正确delete的动态内存中构造的。 这意味着new'它'。