首页 > 解决方案 > 存储指向基类的指针的最佳方式,但能够使用派生类函数

问题描述

我有一个Cell,它可以存储CellContent类型的对象。CellContent必须是一个虚拟类。从CellContent我必须派生类EnemyItem. 所以这个想法是存储一个指向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这个丑陋的东西?

标签: c++inheritance

解决方案


派生类的所有函数,其中:

  • 需要可调用,
  • 虽然变量是基类类型,
  • 但是无需手动从基类类型转换为派生类类型,

应该virtual在基类中声明(并在派生类中被覆盖)。


推荐阅读