1. 程式人生 > >建立不同型別物件時,建構函式和解構函式的呼叫順序

建立不同型別物件時,建構函式和解構函式的呼叫順序

標頭檔案

#ifndef CONS_DES_H
#define CONS_DES_H
#include<iostream>
class base
{
	public:
		base(int);
		~base();
	private:
		int data;
};
#endif

隱藏原始檔:

<span style="color:#330033;">#include "cons_des.h"
#include<iostream>

base::base(int value):data(value)
{
	std::cout<<"Object"<<data<<"constructor";
}
base::~base()
{
	std::cout<<"Object"<<data<<"destructor"<<std::endl;</span><span style="color: rgb(51, 102, 255);">
}</span>

主檔案:

<span style="color:#330033;">#include "cons_des.h"
#include<iostream>
using namespace std;
void create();
base first(1);
int main()
{
	cout<<"     (global created before main)"<<endl;
	base second(2);
	cout<<"     (local automatic in main)"<<endl;
	static base third(3);
    cout << "   (local static in main)" << endl;
    create();
    base sixth(6);
    cout<<"(local automatic in main)"<<endl;
}
void create()
{
	base fourth(4);
	 cout << "   (local automatic in create)" << endl;
	 static base fifth(5);
	 cout << "   (local static in create)" << endl;
	 
}</span>

Object1constructor     (global created before main)
Object2constructor     (local automatic in main)
Object3constructor   (local static in main)
Object4constructor   (local automatic in create)
Object5constructor   (local static in create)
Object4destructor
Object6constructor(local automatic in main)
Object6destructor
Object2destructor
Object5destructor
Object3destructor
Object1destructor


--------------------------------
Process exited after 0.924 seconds with return value 0


請按任意鍵繼續. . .

以上程式中,在主程式執行之前,已經建立第一個物件(即全域性物件first),主程式執行之後,順序地建立自動物件second和靜態物件third。

接著呼叫函式create( ),在create( )中建立自動物件fourth和內部靜態物件fifth,退出create( )時除靜態物件fifth外,刪除其它物件並呼叫它的解構函式,即fourth。

回至主程式後,建立自動物件sixth。

退出主程式時,先刪除主程式內的自動物件並呼叫它們的解構函式,即fourth和second。然後刪除內部靜態物件並呼叫它們的解構函式,即second和fifth。最後刪除主程式外的全域性物件並呼叫它的解構函式,即first。