且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-15 15:19:01

如果你想比较任意类层次结构, bet是使它们多态并使用 dynamic_cast

  class Base {
virtual〜Base(){}
};

class Derived
:public Base {
};

Derived * d = new Derived;
Base * b = dynamic_cast< Base *>(d);

//比较两个指针时,应该把它们
//转换成相同的类型还是没有关系?
bool theSame = dynamic_cast< void *>(b)== dynamic_cast< void *>(d);考虑有时候你不能使用static_cast或从派生类到基类的隐式转换: $ p
  struct A {}; 
struct B:A {};
struct C:A {};
struct D:B,C {};

A * a = ...;
D * d = ...;

/ *静态转换A到D将失败,因为对于一个D * /
/ * dynamic_cast< void *>(a)有多个A将神奇地将您的a转换为D指针,不管
*它指向的两个A。
* /

如果 A 是虚拟继承的,你不能static_cast到 D


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?

If you want to compare arbitrary class hierarchies, the safe bet is to make them polymorphic and use 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:

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.