【发布时间】:2021-11-30 05:08:40
【问题描述】:
我有一个Cell,可以存储CellContent类型的对象。 CellContent 必须是一个虚拟类。从CellContent 我必须派生类Enemy 和Item。所以想法是在Cell 中存储一个指向CellContent 的指针。问题是:在这种情况下,存储指向派生类的指针的最佳方式是什么?
我当前的解决方案不是一个优雅的解决方案,我想改进它。
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 这个丑陋的东西?
【问题讨论】:
-
带有虚函数的普通多态性?
-
看起来像是对LSP的经典违反。
-
作为一般规则,给定的类应该设计用于动态或静态多态性。在这里,移除模板并使用虚函数似乎是合适的选择。
-
@Phil1970, 那么所有可以在派生类中使用的函数都应该在基类中声明为虚函数吗?
-
是的,这就是虚函数的工作方式。虚拟继承本身就是一个复杂的主题,有关更多信息,请参阅您的教科书。 Stackoverflow 并不能很好地替代一本好的 C++ 教科书。
标签: c++ inheritance