Check for derived type (C++)

前端 未结 6 644
暗喜
暗喜 2020-12-09 12:18

How do I check at runtime if an object is of type ClassA or of derived type ClassB? In one case I have to handle both instances separately

ClassA* SomeClass:         


        
6条回答
  •  暖寄归人
    2020-12-09 12:49

    Others have pointed out that switching on types is usually a bad idea, so I won't. If you really have to do it, you can use the typeid operator to switch on the dynamic type of an object:

    ClassA* SomeClass::doSomething ( ClassA* a )
    {
        if (typeid(*a) == typeid(ClassA)) {
            /* parameter is of type base class */
        } else if (typeid(*a) == typeid(ClassB)) {
            /* a specific derived class */ 
        } else {
            /* some other derived class */
        }
    }
    

    dynamic_cast is similar, but tests for convertibility, not equality:

    ClassA* SomeClass::doSomething ( ClassA* a )
    {
        if (ClassB *b = dynamic_cast(a)) {
            /* parameter is, or is derived from, ClassB */
        } else {
            /* parameter is, or is derived from, ClassA but not ClassB */ 
        }
    }
    

    These only work if ClassA is polymorphic (that is, it has at least one virtual function).

提交回复
热议问题