程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++ - 虛繼承(virtual inheritance)的構造(construct)和析構(destruct)順序

C++ - 虛繼承(virtual inheritance)的構造(construct)和析構(destruct)順序

編輯:C++入門知識

虛繼承(virtual inheritance)的構造(construct)和析構(destruct)順序

多重繼承的時候, 構造順序是 虛繼承按順序優先, 再次是其他按順序, 由基類至派生類; 析構順序正好相反;

代碼如下:

/*
 * cppprimer.cpp
 *
 *  Created on: 2014.1.10
 *      Author: Spike
 */

/*eclipse cdt, gcc 4.8.1*/

#include 
#include 

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!


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved