C++中的继承关系容易导致二义性,但是使用虚基类能够避免二义性,其源码如下
1 class Anamal{ 2 public: 3 virtual void eat() = 0; 4 virtual void sleep(){ 5 cout<<"ZZZZZZZZZZZZZ........"<<endl; 6 } 7 }; 8 class Dog:public virtual Anamal{ 9 public: 10 virtual void eat(){ 11 cout<<"Dog eat food"<<endl; 12 } 13 }; 14 class Bird:public virtual Anamal{ 15 public: 16 virtual void eat(){ 17 cout<<"Bird eat food"<<endl; 18 } 19 }; 20 21 class DogBird:public Dog,public Bird{ 22 public: 23 virtual void eat(){ 24 Dog::eat(); 25 } 26 }; 27 void main(int argc, char **argv) 28 { 29 DogBird db; 30 db.eat(); 31 db.sleep(); 32 }
其中调用sleep的方法中就避免了二义性,如果不是用虚基类则当调用sleep方法时,就不知道到底是调用子类Dog还是子类Bird继承的sleep方法。