本文地址: http://blog.csdn.net/caroline_wendy/article/details/18089215
虛繼承主要是避免基類重復被繼承, 包含多個相同基類, 導致歧義性, 使用虛基類(virtual base class)繼承, 可以使派生對象只包含一份基類文件.
如果不使用虛繼承, 則派生類需要提供一份自己的示例版本,
參見: http://blog.csdn.net/caroline_wendy/article/details/18077235
代碼:
/* * cppprimer.cpp * * Created on: 2014.1.10 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include#include class ZooAnimal { public: void zooprint (void) { std::cout << "Zoo Animal!" << std::endl; } }; class Raccoon : public virtual ZooAnimal { public: void raccprint (void) { std::cout << "Raccoon!" << std::endl; } }; class Bear : public virtual ZooAnimal { public: void bearprint (void) { std::cout << "Bear!" << std::endl; } }; class Panda : public Bear, public Raccoon { public: void pandprint (void) { std::cout << "Panda!" << std::endl; } }; void dance (Bear& B) { B.bearprint(); } void rummage (Raccoon& R) { R.raccprint(); } int main (void) { Panda P; P.zooprint(); dance(P); rummage(P); }
Zoo Animal! Bear! Raccoon!