12

在这种情况下比较指针时,我想了解一些有关最佳实践的信息:

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

2 回答 2

5

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

于 2011-04-14T11:49:53.880 回答
5

如果你想比较任意的类层次结构,安全的选择是让它们多态并使用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是虚拟继承的,则不能将 static_cast 转换为一个D

于 2011-04-14T11:59:42.403 回答