当前位置:天才代写 > tutorial > C语言/C++ 教程 > C++中虚担任的结构(construct)和析构(destruct)顺序

C++中虚担任的结构(construct)和析构(destruct)顺序

2017-11-02 08:00 星期四 所属: C语言/C++ 教程 浏览:583

虚担任(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!

 

    关键字:

天才代写-代写联系方式