在这个程序中:
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;
}
我对这个程序几乎没有疑问:
在执行 static_cast 时,编译器会给出错误
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 类中添加虚拟析构函数时,它变成了多态并且允许动态转换。
我无法理解为什么会这样。