虚拟继承与多继承的区别

虚拟继承应该还说就是建立在多继承的基础上、也就是说无多继承就无所谓的虚拟继承、而虚拟继承的存在也就是为了省下些多重继承的性能、

 

这什么这样说呢、因为迩使用多继承时、如果最终类是通过多个类继承的、而这些类都是由同一个基类继承时、对最终类的实例化就会重复执行、造成性能的浪费

比如

class Human {};

class Mother : public Human {};

class Father : public Human {};

class Son : public Mother, public Father {};

那么这样的话、执行Son类的初始化就会执行两次Human的初始化、Son初始化、引发Mother和Father初始化、而Mother和Father各引发了一次Human的初始化、所以是执行了两次初始化、是不是狠浪费性能呢

 

改成虚拟继承的话、

class Human {};

class Mother : public virtual Human {};

class Father : public virtual Human {};

class Son : public Mother, public Father {};

这样的话、只引发一次Human的初始化、Human初始化发生在Son初始化时、Son初始化时初始化自身和Human、并且引发了Mother和Father的初始化、但Mother和Father并不再初始化Human、这时候、当虚拟继承时、仅在最终派生类负责虚拟继承基类的初始化

posted @ 2012-05-12 11:53  klobodnf  阅读(332)  评论(0编辑  收藏  举报