问题描述
如果对象类型为ClassA或派生类型ClassB,如何在运行时检查?在一种情况下,我必须分别处理两个实例。
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::doSomething ( ClassA* )
{
if( /* parameter is of type base class */) {
} else if { /* derived class */ ) {
}
}
也许我可以说派生类ClassB有一些特殊的能力。但是如何在不改变现有类ClassA的情况下这样做?
Maybe I could say that the derived class ClassB has some special capabilities. But how do I do that without changing the existing class ClassA ?
推荐答案
像那样。通过这样做,你将你的方法紧密地耦合到派生类 ClassA
。你应该使用多态性。在类A中引入虚拟
方法,在类B中覆盖它,只需在方法中调用它。
It's generally a very bad idea to switch on the exact type like that. By doing this, you are tightly coupling your method to derived classes of ClassA
. You should use polymorphism. Introduce a virtual
method in class A, override it in class B and simply call it in your method.
如果我由于某种原因被迫处理外部函数本身的功能,我会做一些像:
Even if I was forced to handle the functionality in the external function itself for some reason, I would do something like:
class ClassA {
public: virtual bool hasSpecificFunctionality() { return false; }
};
class ClassB : public ClassA {
public: virtual bool hasSpecificFunctionality() { return true; }
};
ClassA* SomeClass::doSomething ( ClassA* arg )
{
if (arg->hasSpecificFunctionality()) {
} else {
}
}
这篇关于检查派生类型(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!