C ++:比较基类和派生类的指针 [英] C++: Comparing pointers of base and derived classes
本文介绍了C ++:比较基类和派生类的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在比较指针时,我想了解一些最佳做法的相关资讯,例如:
class Base {
};
class Derived
:public Base {
};
Derived * d = new Derived;
Base * b = dynamic_cast< Base *>(d);
//比较两个指针时,应该把它们
//转换成相同的类型还是没有关系?
bool theSame = b == d;
//或者,bool theSame = dynamic_cast< Derived *>(b)== d?
解决方案
如果你想比较任意类层次结构, 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或从派生类到基类的隐式转换: 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.
这篇关于C ++:比较基类和派生类的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文