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?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想比较任意类层次结构,安全的选择是使它们多态并使用
dynamic_cast
考虑到有时您不能使用static_cast或从派生类到基类的隐式转换:
如果
A
是虚拟继承的,您也不能 static_cast 为D
。If you want to compare arbitrary class hierarchies, the safe bet is to make them polymorphic and use
dynamic_cast
Consider that sometimes you cannot use static_cast or implicit conversion from a derived to a base class:
If
A
is inherited virtually, you can't static_cast to aD
either.在上述情况下,您不需要任何转换,简单的
Base* b = d;
就可以了。然后您可以像现在比较一样比较指针。You do not require any cast in the above case, a simple
Base* b = d;
will work. Then you can compare the pointers like you are comparing now.