酱坛子

专注C++技术 在这里写下自己的学习心得 感悟 和大家讨论 共同进步(欢迎批评!!!)

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  66 Posts :: 16 Stories :: 236 Comments :: 0 Trackbacks

公告

王一伟 湖南商学院毕业 电子信息工程专业

常用链接

留言簿(19)

我参与的团队

搜索

  •  

积分与排名

  • 积分 - 382342
  • 排名 - 63

最新随笔

最新评论

阅读排行榜

评论排行榜

class   shape   {  
  public:  
            shape(int){}  
  };  
   
  class   circle:   public   shape   {  
  public:  
          circle(int):   shape(1){}  
  };  
   
  class   square:   public   shape   {  
  public:  
          square(int):   shape(1){}  
  };  
   
  class   bizzare:   public   circle,   public   square   {  
  public:  
          bizzare():   circle(1),   square(1){}  
  };  
  这里用的就是一般的多重继承,没有虚拟继承的存在。在bizzare(之所以叫这个名字,因为……从circle和square继承而来实在是够怪异的了,呵呵)类的member   initialization   list中,只需要写circle和square类的构造函数就可以了,后两者再分别调用它们的基类shape(分别的两个实例)的构造函数。  
   
  而如果是虚拟继承:  
  class   shape   {  
  public:  
            shape(int){}  
  };  
   
  class   circle:   public   virtual   shape   {  
  public:  
          circle(int):   shape(1){}  
  };  
   
  class   square:   public   virtual   shape   {  
  public:  
          square(int):   shape(1){}  
  };  
   
  class   bizzare:   public   circle,   public   square   {  
  public:  
          bizzare():   circle(1),   square(1),   shape(1){}  
  };  
  则必须在most   derived的派生类中初始化虚拟基类。  
   
  TC++PL上肯定有说的,在class   hierarchy那章。




这是语言规定。因为只有一个sharp对象,从哪个基类构造都有问题(因为它们可能调用虚基类的不同构造函数,产生二义性),所以标准规定必须在most   derived构造时显式或隐式(虚基类有缺省构造函数时)构造虚基类。楼主的例子里sharp没有缺省构造函数,所以必须显式构造。  
  TC++PL里有:  
  The   constructor   of   a   virtual   base   is   invoked   (implicitly   or   explicitly)   from   the   constructor   for   the   complete   object   (the   constructor   for   the   most   derived   class).


虚拟继承:发生在多重继承上,比如:一个类继承两类,但是这两个类都继承一个类。(类图出现环),即“孙子”到“爷爷”的路径超过一条时,使用,要不会有两个“爷爷”  
   
  虚函数:与继承完成多态工作。是面向对象关键中的关键。由于面向对象的设计是自顶向下的,先功能定义在实现。继承主要有实现继承和接口继承,都需要多态  
posted on 2007-09-21 06:47 @王一伟 阅读(1345) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理