简体   繁体   English

在C ++中使用dynamic_cast是不好的设计

[英]Is it bad design to use dynamic_cast in c++

I have a class CAbstractNode and it has 5 derived classes 我有一个CAbstractNode类,它有5个派生类

out of 5, only 2 (special) need a method SetValue() and a member int nVal; 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...
}

shall I go with dynamic cast for 2 derived classes (as shown above) 我应该对2个派生类进行动态转换吗(如上所示)

or 要么

shall I take setValue() method as virtual in base(CAbstractNode) and implement in 2 derived classes and this method keeping empty in other 3 derived classes ? 我是否应该在base(CAbstractNode)中将setValue()方法作为虚拟方法并在2个派生类中实现,并且此方法在其他3个派生类中保持空白?

Problem is not dynamic_cast itself, it is a symptom. 问题不是dynamic_cast本身,而是一种症状。 In your case if myFunction accepts CAbstractNode interface it should work with it. 在您的情况下,如果myFunction接受CAbstractNode接口,则应该使用它。 But for whatever reason it has to know about Derived_02 and call specific method of that, which most probably shows that CAbstractNode interface is poorly designed. 但是无论出于何种原因,都必须了解Derived_02并调用该方法的特定方法,这很可能表明CAbstractNode接口的设计不良。 Or at least not properly designed, but it is up to you to decide if you want to fix interface or keep workaround. 或至少没有经过适当设计,但是由您决定是否要修复接口或保留解决方法。 Remember engineering is mostly about compromises, perfect design quite often is not reachable or not practical. 请记住,工程主要是折衷方案,而完美的设计往往是无法达到或不切实际的。

dynamic_cast is a code smell dynamic_cast是一种代码异味

Usually this can be solved overloading the functions or using virtual functions. 通常,可以通过重载功能或使用虚拟功能来解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM