比较基类和派生类的指针

C++: Comparing pointers of base and derived classes

本文关键字:指针 派生 基类 比较      更新时间:2023-10-16

我想了解一些关于比较指针的最佳实践的信息,例如:

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?

如果您想比较任意的类层次结构,最安全的方法是使它们为多态并使用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

在上述情况下,您不需要任何强制转换,简单的Base* b = d;将工作。然后你可以像现在这样比较指针