我想了解一些有关在如下情况下比较指针的最佳实践:
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?
static_cast
将它们都转换为共同的基类。当然,前提是您知道这个共同的基类。否则:如果一个指针是另一个指针的基类型,编译器会自动进行转换。 - James Kanze