今天遇到一个虚拟继承引起的类型转换错误,网上查到相关资料记录如下:
class VirtualBase
{
public:
virtual class Derived* asDerived() = 0;
};
class Derived : virtual public VirtualBase
{
public:
virtual Derived* asDerived();
};
Derived*
Derived::asDerived()
{
return this;
}
void
main()
{
Derived d;
Derived* dp = 0;
VirtualBase* vp = (VirtualBase*)&d;
dp = (Derived*)vp; // ERROR! Cast from virtual base class pointer
dp = vp->asDerived(); // OK! Cast in function asDerived
}
Virtual base classes give rise to other type conversion problems. It is possible to convert a pointer, to an instance of a class which has a virtual base class, to a pointer to an object of that virtual base class. The opposite conversion is not allowed, i.e. the type conversion is not reversible. For this reason, we do not recommend the conversion of a derived class pointer to a virtual base class pointer.
评论