对不起,标题的措辞;我不知道如何做得更好。但是我的问题的要点是:
#include <iostream>
using namespace std;
class Base {};
class Base2 {};
class C : public Base, public Base2 {};
class D : public Base {};
void isDerivedFromBase2(Base *p) {
if (...) { /* test whether the "real object" pointed by p is derived from Base2? */
cout << "true" << endl;
}
cout << "false" << endl;
}
int main() {
Base *pc = new C;
Base *pd = new D;
isDerivedFromBase2(pc); // prints "true"
isDerivedFromBase2(pd); // prints "false"
// ... other stuff
}
如何测试由其基类指针表示的对象Base *
是否从另一个基类派生Base2
?
您可以这样执行dynamic_cast
:
if (dynamic_cast<Base2 *>(p)) {
与这种方法不同,typeid
它不需要包含额外的头,但是它也依赖于RTTI(这意味着这些类需要是多态的)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句