虛繼承(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!