的情況下,在這個程序:鑄造在多個虛擬繼承
class Top
{
public:
int a;
};
class Left : virtual public Top
{
public:
int b;
};
class Right : virtual public Top
{
public:
int c;
};
class Bottom : public Left, public Right
{
public:
int d;
};
class AnotherBottom : public Left, public Right
{
public:
int e;
int f;
};
int main()
{
Bottom* bottom1 = new Bottom();
AnotherBottom* bottom2 = new AnotherBottom();
Top* top1 = bottom1;
Top* top2 = bottom2;
Left* left = static_cast<Left*>(top1);
return 0;
}
我有一個關於這個計劃幾個疑惑:
做編譯器給出了錯誤
error: cannot convert from base ‘Top’ to derived type ‘Left’ via virtual base ‘Top
即使在動態鑄造上也會給出錯誤
error: cannot dynamic_cast ‘top1’ (of type ‘class Top*’) to type ‘class Left*’ (source type is not polymorphic)
因此,在Top類中添加虛擬析構函數時,它變成多態,並允許動態轉換。
我無法理解爲什麼會發生這種情況。
閱讀這個非常類似的問題:http://stackoverflow.com/questions/3747066/c-cannot-convert-from-base-a-to-derived-type-b-via-virtual-base-a –