【发布时间】:2016-08-23 08:17:29
【问题描述】:
当尝试访问派生类行为时,我读到的最常见的方法是使用dynamic_casts,即dynamic_cast<DerivedA*>(BasePtr)->DerivedAOnlyMethod()。这不是很漂亮,但每个人都明白发生了什么。
现在我正在编写一个代码,其中这种转换由导出到基类的虚拟函数处理,对于每个派生类,即:
class Base
{
public:
virtual DerivedA* AsDerivedA() { throw Exception("Not an A"); }
virtual DerivedB* AsDerivedB() { throw Exception("Not a B"); }
// etc.
};
class DerivedA : public Base
{
public:
DerivedA* AsDerivedA() { return this; }
};
// etc.
然后使用BasePtr->AsDerivedA()->DerivedAOnlyMethod()。恕我直言,这使基类变得混乱,并暴露了它不应该需要的派生类的知识。
我太缺乏经验,无法肯定地说哪个更好,所以我正在寻找支持和反对这两种结构的论据。哪个更惯用?他们在性能和安全性方面如何比较?
【问题讨论】:
-
这些函数打破了[开闭原则][1]。如果要添加 C 类,则需要更改 Base 类以添加 AsDerivedC。 [1]:en.wikipedia.org/wiki/Open/closed_principle
标签: c++ inheritance casting