虚继承(virtual inheritance)的构造(construct)和析构(destruct)顺序
在多重继承的时候, 构造顺序是 虚继承按顺序优先, 再次是其他按顺序, 由基类至派生类; 析构顺序正好相反;
代码如下:
/* * cppprimer.cpp * * Created on: 2014.1.10 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> #include <string> class ZooAnimal { public: ZooAnimal () { std::cout << "ZooAnimal Constructor!" << std::endl; } void zooprint (void) { std::cout << "Zoo Animal!" << std::endl; } }; class Bear : public virtual ZooAnimal { public: Bear (){ std::cout << "Bear Constructor!" << std::endl; } void bearprint (void) { std::cout << "Bear!" << std::endl; } }; class Character { public: Character () { std::cout << "Character Constructor!" << std::endl; } }; class BookCharacter : public Character { public: BookCharacter () { std::cout << "BookCharacter Constructor!" << std::endl; } }; class ToyAnimal { public: ToyAnimal () { std::cout << "ToyAnimal Constructor!" << std::endl; } }; class TeddyBear : public BookCharacter, public Bear, public virtual ToyAnimal { public: TeddyBear () { std::cout << "TeddyBear Constructor!" << std::endl; } }; int main (void) { TeddyBear TB; }
输出:
ZooAnimal Constructor! ToyAnimal Constructor! Character Constructor! BookCharacter Constructor! Bear Constructor! TeddyBear Constructor!