任意のクラス階層を比較したい場合、安全な方法は、それらを多形にして使用することです。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
。