拷貝構造函數

6.9 構造函數與析構函數的比較

1、 拷貝構造函數的定義:

拷貝構造函數是一種特殊的成員函數。該函數的功能是用一個已有的對象的值來初始化一個新構造的對象。拷貝構造函數實際上也是構造函數,它是在初始化時被調用來將一個已知對象的數據成員的值拷貝給正在創建的另一個同類的對象。

拷貝構造函數的定義格式爲:

< 類名 >::< 拷貝構造函數名 >(const < 類名 >&< 引用名 >)

其中 < 拷貝構造函數名 > 與類名相同。形參是一個該類的引用,且只能有一個形參。

2、 拷貝構造函數被調用的情況:

⑴用一個已知對象的值去初始化另一個對象。

例如: Tdate today(2001,12,1);

Tdate tom=today; // 用 today 的值初始化 tom.

⑵對象作爲函數的參數傳遞時,把實參對象的值傳給形參對象。

⑶當對象作爲函數的返回值時,如 return W, 系統將調用對象 W 來初始化一個匿名對象,需要調用拷貝構造函數。

例如: void f1(Tdate d)

{

…..

}

void main()

{

Tdate c;

f1(c );

}

例 14 :對於上例的 employee 類,改寫如下:

#include<iostream.h>

class employee

{

public:

employee(char *na,char *street,char *city,char *di,char *po);

employee(employee & qq);

void changeName(char *);

void display();

~employee()

{

cout<<"Destructing object./n";

}

protected:

char *name;

char *street;

char *city;

char *district;

char *post;

};

employee::employee(char *na,char *st,char *ci,char *di,char *po)

{

name=na;

street=st;

city=ci;

district=di;

post=po;

}

employee::employee(employee &qq)

{

name=qq.name;

street=qq.street;

city=qq.city;

district=qq.district;

post=qq.post;

cout<<"Copy constructor function called/n";

}

void employee::changeName(char *na)

{

name=na;

}

void employee::display()

{

cout<<name<<endl;

cout<<street<<endl;

cout<<city<<endl;

cout<<district<<endl;

cout<<post<<endl;

}

void main()

{

employee person1("Mary","Nan Jing Lu120","nanjing","Jiangsu","20002");

employee person2=person1;

person2.display();

}

運行結果爲:

Copy structor function called.

Mary

Nan Jing Lu120

nanjing

jiangsu

20002

destructing object.

destructing object.

例 15 分析下列程序的輸出結果。這裏沿用例 14 的 employee 類。

#include<iostream.h>

#include”employee.h”

employee f1(employee q);

void main()

{

employee person1(“Join”,” Beijing Road 220” ,

” Beijing ”,”Zhixiashi”,” 10080” );

employee person2(“Nobody”,”No address”,”Nowhere”

,”Nodistrict”,” 00000” );

employee person3=person1;

person2=f1(person3);

person2.display();

}

employee f1(employee q)

{

cout<<”this is function called./n”;

employee r(“Wang Lan”,”gansulu”,”beijing”,”Zhixiashi”,” 10020” );

r=q;

return r;

}

運行結果:

Copy constructor function called.

Copy constructor function called.

this is function called.

Copy constructor function called.

Destructing object.

Destructing object.

Destructing object.

Join

Beijing Road 220

Beijing

Zhixiashi

10080

Destructing object.

Destructing object.

Destructing object.

說明:從該程序的輸出結果可以看出:

•  拷貝構造函數共使用了三次。第一次是執行 employee person3=person1; 語句時,對對象 person3 初始化。第二次是在調用函數 f1() 函數時,實參 person3 給形參 q 進行初始化時,即實參向形參傳遞值時。第三次是在執行 f1() 函數中的返回語句 return rl; 時,系統用返回值初始化一個匿名對象時使用了拷貝構造函數。

•  析構函數一共調用了六次。在退出 f1() 函數時,該函數中定義的對象將被釋放,系統自動調用其析構函數。共調用了二次,用來析構對象 q 和 r 。在返回主函數 main() 後,用賦值運算符將其匿名對象的值賦給對象 person2 ,然後釋放匿名對象,這是又調用一次析構函數。最後退出整個程序時,又調用了三次析構函數,分別釋放主函數中定義的對象 person3,person2,person1 。所以總共調用了六次析構函數。

發佈了30 篇原創文章 · 獲贊 1 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章