【问题标题】:C++: Comparing pointers of base and derived classesC++:比较基类和派生类的指针
【发布时间】:2011-04-14 11:47:19
【问题描述】:

我想了解一些关于在这种情况下比较指针时的最佳做法的信息:

class Base {
};

class Derived
    : public Base {
};

Derived* d = new Derived;
Base* b = dynamic_cast<Base*>(d);

// When comparing the two pointers should I cast them
// to the same type or does it not even matter?
bool theSame = b == d;
// Or, bool theSame = dynamic_cast<Derived*>(b) == d?

【问题讨论】:

    标签: c++ inheritance pointers dynamic-cast


    【解决方案1】:

    如果你想比较任意类层次结构,安全的办法是让它们多态并使用dynamic_cast

    class Base {
      virtual ~Base() { }
    };
    
    class Derived
        : public Base {
    };
    
    Derived* d = new Derived;
    Base* b = dynamic_cast<Base*>(d);
    
    // When comparing the two pointers should I cast them
    // to the same type or does it not even matter?
    bool theSame = dynamic_cast<void*>(b) == dynamic_cast<void*>(d);
    

    考虑到有时您不能使用 static_cast 或从派生类到基类的隐式转换:

    struct A { };
    struct B : A { };
    struct C : A { };
    struct D : B, C { };
    
    A * a = ...;
    D * d = ...;
    
    /* static casting A to D would fail, because there are multiple A's for one D */
    /* dynamic_cast<void*>(a) magically converts your a to the D pointer, no matter
     * what of the two A it points to.
     */
    

    如果A 是虚拟继承的,您也不能静态转换为D

    【讨论】:

    • 另一个安全的选择是使用static_cast 将它们都转换为一个共同的基础。当然,前提是你知道共同的基础。否则:如果一个指针是另一个指针的基类型,编译器将自动进行转换。
    【解决方案2】:

    在上述情况下您不需要任何演员表,一个简单的Base* b = d; 就可以了。然后你可以像现在比较的那样比较指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多