C++多态:如何测试一个类派生自另一个基类?

Lee*_*hai 3 c++ polymorphism

对不起标题的措辞; 我不知道如何让它变得更好.但我的问题的主旨是:

#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
}
Run Code Online (Sandbox Code Playgroud)

如何测试由其基类指针表示的对象Base *是否来自另一个基类Base2

use*_*670 7

你可以这样执行dynamic_cast:

 if (dynamic_cast<Base2 *>(p)) {
Run Code Online (Sandbox Code Playgroud)

online_compiler

typeid此方法不同,不需要包含额外的头,但它也依赖于RTTI(这意味着这些类需要是多态的).

  • @Leedehai:你在运行时请求输入类型信息,我相信这些单词的顺序与RTTI不同;). (2认同)