代码之家  ›  专栏  ›  技术社区  ›  Leedehai

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

  •  3
  • Leedehai  · 技术社区  · 6 年前

    对标题的措辞表示抱歉,我不知道如何改进。但我的问题是:

    #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 ?

    2 回复  |  直到 6 年前
        1
  •  7
  •   user7860670    6 年前

    你可以表演 dynamic_cast 这样地:

     if (dynamic_cast<Base2 *>(p)) {
    

    online_compiler

    不同于 typeid 这个类不需要包含额外的头,但是它也依赖于rtti(这意味着这些类需要是多态的)。

        2
  •  0
  •   Aganju    6 年前

    这听起来像是X-Y问题。

    对rtti的需求(或者对派生它的类的对象进行测试的需求)通常是错误设计的标志。- 你根本不应该需要 这样的测试/信息。
    如果层次结构设计良好,那么虚拟函数将承担这些测试的角色。

    为了找出设计不完善的地方,问问自己,“一旦我掌握了这些信息,我将如何处理?”答案总是“我会做一个if/switch/……以不同的方式对待他们;正确的解决方法是 相同的 方法-调用一个虚拟方法,并且每个对象都具有正确的虚拟方法的知识,知道需要做什么。