C++:比较基类和派生类的指针

14

我想了解一些有关在如下情况下比较指针的最佳实践:

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?
2个回答

7

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

1
另一个安全的选择是使用static_cast将它们都转换为共同的基类。当然,前提是您知道这个共同的基类。否则:如果一个指针是另一个指针的基类型,编译器会自动进行转换。 - James Kanze

5
在上述情况下,您不需要任何强制类型转换,只需使用简单的Base * b = d;即可。然后您可以像现在一样比较指针。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接