c++ - 存储指向基类的指针的最佳方式,但能够使用派生类函数
问题描述
我有一个Cell
,它可以存储CellContent
类型的对象。CellContent
必须是一个虚拟类。从CellContent
我必须派生类Enemy
和Item
. 所以这个想法是存储一个指向CellContent
内部的指针Cell
。问题是:在这种情况下,存储指向派生类的指针的最佳方式是什么?
我目前的解决方案不是一个优雅的解决方案,我想改进它。
class Cell
{
public:
template<class T> void setCellContent(std::shared_ptr<T> cellContent)
{
_cellContent = std::dyanmic_pointer_cast<CellContent>(cellContent);
if (std::is_same<T, Enemy>::value = true) {
_cellContentType = CellContentType::ENEMY;
} else if (std::is_same<T, Item>::value = true) {
_cellContentType = CellContentType::ITEM;
}
}
template<class T> std::shared_ptr<T> getCellContent()
{
return std::dynamic_pointer_cast<T>(_cellContent);
}
CellContentType getCellContentType()
{
return _cellContentType;
}
std::shared_ptr<CellContent> _cellContent;
CellContentType _cellContentType;
}
int main()
{
auto enemy = std::make_shared<Enemy>();
Cell cell;
cell.setCellContent<Enemy>(enemy);
if (CellContentType::ENEMY == cell.getCellContentType()) {
cell.getCellContent<Enemy>();
} else if (CellContentType::ITEM == cell.getCellContentType()) {
cell.getCellContent<Item>();
}
}
如果在 main 中,我如何避免使用if
这个丑陋的东西?
解决方案
派生类的所有函数,其中:
- 需要可调用,
- 虽然变量是基类类型,
- 但是无需手动从基类类型转换为派生类类型,
应该virtual
在基类中声明(并在派生类中被覆盖)。
推荐阅读
- python - 用列表绘制小提琴图
- ios - Visual Studio for Mac - 没有匹配的配置文件
- laravel - 使用 Milon Barcode Library 将 QR 码重定向到网站
- python - 使用 pip 安装 jupyterlab 时遇到问题
- java - 寻找 REGEX 以匹配选择关闭字符串的组
- android - 如何将主页顶部的个人资料选项卡与颤动对齐?
- c# - 我收到“该进程无法访问该文件,因为它正被另一个进程使用”错误。有任何想法吗?
- python - Tkinter:发送变量以循环运行
- python - 在sqlite中插入大量数据
- javascript - React Hooks - 使用 lodash 的 deepCopy 不会导致重新渲染