【发布时间】:2020-05-10 12:57:25
【问题描述】:
我刚刚开始学习智能指针,但在实现它们时遇到了一些麻烦。
我正在为一个棋盘游戏编写代码,该棋盘游戏有一个抽象的棋子基类,例如一个棋子的派生类:
class pieces {
public:
virtual ~pieces() {};
};
class piece1:public pieces {
private:
std::string id{ "" };
std::string team{ "" };
public:
piece1(std::string identification, std::string red_or_blue_team);
~piece1() { std::cout << "destructor called." << std::endl; }
};
棋盘游戏本身也有一个单独的抽象类,例如某些特定棋盘游戏的派生类,例如国际象棋:
typedef std::map < int, std::shared_ptr<pieces> > grid;
class board_game {
protected:
grid the_board;
public:
virtual std::shared_ptr<pieces> create_piece(std::string type, int id, std::string team) = 0;
};
class chess: public board_game {
public:
std::shared_ptr<pieces> create_piece(std::string type, int id, std::string team);
};
目标是创建指向映射容器上的值的共享指针,然后随着类中的其他方法移动该块(未显示),该指针将在所有权中移动。
所以作为一个起点,我有函数 create_piece:
std::shared_ptr<pieces> chess::create_piece(std::string type, int id, std::string team)
{
if (type == "piece1_type") {
return new piece1(id,team);
}
}
这会在return new piece1(id,team); 行返回错误
错误(活动)E0415 不存在合适的构造函数来从“piece1*”转换为“std::shared_ptr”
并且 :
'return': 无法从 'flag *' 转换为 'std::shared_ptr'。
我认为解决此问题的方法与更改我对 piece1 的参数化构造函数的实现有关,但我真的不知道该怎么做。 piece1 的构造函数:
flag::flag(std::string identification, std::string red_or_blue_team)
{
id = identification;
team = red_or_blue_team;
}
我在这里看到了类似的article,但我无法将其有效地应用于我自己的问题。
【问题讨论】:
标签: c++ c++11 visual-c++