如何解决C ++:比较基类和派生类的指针
| 我希望在诸如此类的情况下比较指针时有关最佳做法的一些信息: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?
解决方法
如果要比较任意的类层次结构,安全的选择是使它们多态并使用
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
。
,在上述情况下,您不需要任何强制转换,只需简单的Base* b = d;
就可以。然后,您可以像现在进行比较一样比较指针。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。