正文

强制类型转换的错误2012-03-02 15:09:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/aurora/53331.html

分享到:


今天遇到一个虚拟继承引起的类型转换错误,网上查到相关资料记录如下:
   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. 

阅读(1740) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册