菱形继承:为什么向下转换不起作用? [英] Diamond shape inheritance: why downcasting is not working?
本文介绍了菱形继承:为什么向下转换不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
提前致谢.我正在DevC ++环境中从事C ++项目.
我观察到的是,在菱形继承的情况下,向上转换为基类然后向下转换为派生类是不可能的吗?
你能告诉我为什么会这样吗?
以下是我正在运行的代码.
Hi,
Thanks in advance. I am working on C++ project in DevC++ environment.
What I have observed is that in case of diamond-shape inheritance, upcasting to base class and then downcasting to derived class back is not possible?
Could you please tell me why is this so?
Following is the code which I am running.
class DiamondBase
{
public:
int DiamondBaseData1;
};
// virtual base class will share base-class-subobject with DiamondDerived2 class
class DiamondDerived1: virtual public DiamondBase
{
public:
int DiamondBaseData2;
void DiamondDerived1Fun(void){};
};
// virtual base class will share base-class-subobject with DiamondDerived1 class
class DiamondDerived2: virtual public DiamondBase
{
public:
int DiamondBaseData3;
void DiamondDerived2Fun(void){};
};
class VirtualBaseDerived: public DiamondDerived1, public DiamondDerived2
{
public:
int DiamondBaseData4;
};
void Main()
{
DiamondDerived2 obj1;
DiamondBase* pBase = &obj1; // upcasting of DiamondDerived2
((DiamondDerived1*)pBase)->DiamondDerived1Fun(); // error: cannot convert from base to derived via "virtual-base"
((DiamondDerived2*)pBase)->DiamondDerived2Fun(); // error: cannot convert from base to derived via "virtual-base"
}
推荐答案
签出
http://stackoverflow.com/questions/3747066/c-cannot-convert-from-base-a-to-derived-type-b-via-virtual-base-a [dynamic_cast.
Check out
http://stackoverflow.com/questions/3747066/c-cannot-convert-from-base-a-to-derived-type-b-via-virtual-base-a[^]
Note that to usedynamic_cast
, you must have ''polymorphic classes'', i. e. your classes should have at least one virtual method. Try defining, say, a virtual destructor for each of your classes. Then usedynamic_cast
.
要正确地转换为具有虚拟基类的类,某些
有关对象实际类型的运行时信息
可能需要强制转换.
如果我们使用 dynamic_cast ,就可以实现这一点.另一方面,您正在static_cast中尝试的常规转换没有这样的功能.
To perform correct cast to a class with virtual base classes some
runtime information about the actual type of the object being
casted may be required.
And this can be acheived if we use dynamic_cast. On the other hand, the normal casting you are trying in static_cast which do not have a facility like this.
这篇关于菱形继承:为什么向下转换不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文