没有可行的超载'='用于shared_ptr
no viable overloaded '=' for 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;
}
我收到以下错误:
没有可行的重载"=" 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_ptr
将delete
它拥有的指针(除非您提供不同的deleter
(,因此您需要使用new
(或std::make_shared()
(来确保对象是在可以正确delete
的动态内存中构造的。 这意味着new
'它'。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 用于访问容器<T>数据成员的正确 API
- 重载操作程序时出错>>用于类中的字符串 memebr
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- C++中的cin.ignore()函数不适用于整个流
- 没有用于初始化C++中的变量模板的匹配构造函数
- 用于C++中带有数组和指针的循环
- 为什么它不适用于Visual 2019的原因
- 使用在用于SFINAE的void_t中具有参数的方法
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 重载==不适用于二进制树
- Insert函数不适用于2 if语句C++
- 用于矢量处理的多个线程
- 使外部项目可用于find_package CMake
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- 为什么模数运算符不适用于该代码
- 并行用于C++17中数组索引范围内的循环
- 将fold表达式与std::一起用于两个元组
- shared-ptr-C++shared_ptr与unique_ptr用于资源管理