虚担任主要是制止基类反复被担任, 包括多个沟通基类, 导致歧义性, 利用虚基类(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 <iostream> #include <string> 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!
作者:csdn博客 Spike_King