简体   繁体   English

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

[英]C++: Comparing pointers of base and derived classes

I'd like some information about best practices when comparing pointers in cases such as this one: 在比较像这样的情况下的指针时,我想了解一些关于最佳实践的信息:

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?

You do not require any cast in the above case, a simple Base* b = d; 在上述情况下你不需要任何演员,简单的Base* b = d; will work. 将工作。 Then you can compare the pointers like you are comparing now. 然后你可以比较你现在比较的指针。

If you want to compare arbitrary class hierarchies, the safe bet is to make them polymorphic and use dynamic_cast 如果你想比较任意类层次结构,安全的做法是使它们具有多态性并使用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);

Consider that sometimes you cannot use static_cast or implicit conversion from a derived to a base class: 考虑到有时您不能使用从派生到基类的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.
 */

If A is inherited virtually, you can't static_cast to a D either. 如果A是虚拟继承的,那么你也不能将static_cast转换为D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM