我有一个 CAbstractNode 类,它有 5 个派生类
在 5 个中,只有 2 个(特殊)需要一个方法 SetValue() 和一个成员 int nVal;
//myFunction is virtual function of base(cAbstractNode) implemented in 2 special derived classes
myFunction(CAbstractNode * obj, int val)
{
Derived_02 nodeObj = dynamic_cast<Derived_02*>(obj);
if(res != NULL)
{
nodeObj->setValue(val);
}
//remaining code goes here...
}
//myFunction is virtual function implemented in remaining 3 derived classes ( setValue() is not needed here)
myFunction(CAbstractNode * obj, int val)
{
//remaining code goes here...
}
我应该为 2 个派生类使用动态转换吗(如上所示)
或
我应该将 setValue() 方法作为 base(CAbstractNode) 中的虚拟方法吗 并在 2 个派生类中实现并且此方法在其他 3 个派生类中保持为空?
最佳答案
问题不是 dynamic_cast
本身,而是一种症状。在您的情况下,如果 myFunction
接受 CAbstractNode
接口(interface),它应该可以使用它。但无论出于何种原因,它必须了解 Derived_02
并调用其特定方法,这很可能表明 CAbstractNode
接口(interface)设计不当。或者至少设计不当,但由您决定是要修复界面还是保留解决方法。请记住,工程主要是妥协,完美的设计往往无法实现或不切实际。
关于c++ - 在 C++ 中使用 dynamic_cast 是不好的设计吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43307674/