【正文】
第二部分面向?qū)ο蟪绦蛟O(shè)計 第十一章 構(gòu)造函數(shù)和析構(gòu)函數(shù) 11 167。 類與對象 第十一章 目 錄 167。 析構(gòu)函數(shù) 167。 構(gòu)造函數(shù) 167。 帶參數(shù)的構(gòu)造函數(shù) 167。 重載構(gòu)造函數(shù) 167。 缺省構(gòu)造函數(shù) 第十一章小結(jié) 167。 拷貝構(gòu)造函數(shù) 167。 拷貝構(gòu)造函數(shù)的其他用處 C++ 中構(gòu)造函數(shù)和析構(gòu)函數(shù)是類的特殊成員函數(shù)。 構(gòu)造函數(shù)用于創(chuàng)建類對象,初始化其成員。 析構(gòu)函數(shù)用于撤銷類對象。 本章介紹構(gòu)造函數(shù)、析構(gòu)函數(shù)、缺省構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)等相關(guān)內(nèi)容。 第十一章 構(gòu)造函數(shù)和析構(gòu)函數(shù) 一個類描述一類事物,描述這些事物所應(yīng)具有的屬性。 對象是類的一個實例,它具有確定的屬性。 如學(xué)生類與某學(xué)生對象。 類的名字只有一個,但由該類創(chuàng)建的對象可以任意多個。 屬于不同類的對象可以在不同時刻、不同環(huán)境分別創(chuàng)建或撤銷。 與定義變量相同,可定義具有不同存儲屬性的各類對象。定義對象時, C++ 編譯器為其分配存儲空間 (如果需要 )。 167。 類與對象 例如:下面程序定義了兩個類,創(chuàng)建了全局對象和局部對象,靜態(tài)對象和堆對象。 class Desk //define class Desk { public: int weight。 int high。 int width。 int length。 }。 class Stool //define class Stool { public: int weight。 int high。 int width。 int length。 }。 Desk da。 //globle object da Stool sa。 //globle object sa void fn() { static Stool ss。 //local static object Desk da。 //local object //…… } void main() { Stool bs。 //local object Desk *pd=new Desk。 //heap object Desk nd[50]。 //local array of object //…… delete pd。 //clean up object and release resources } 前面已經(jīng)介紹過變量定義時若未顯式初始化,全局變量和靜態(tài)變量在定義時初值為 0,局部變量在定義時初值為隨機(jī)數(shù)。 與定義變量不同,一旦建立一個對象,對象通常都需要有一個有意義的初值。 C++ 建立和初始化對象的過程專門由該類構(gòu)造函數(shù)完成。 對象建立時,調(diào)用該構(gòu)造函數(shù),給對象分配存儲空間并進(jìn)行初始化。 當(dāng)對象撤銷時,調(diào)用析構(gòu)函數(shù)作善后處理。 167。 構(gòu)造函數(shù) 類創(chuàng)建對象時需要對對象初始化,但初始化任務(wù),只有由成員函數(shù)完成,因此,在類中必須定義一個具有初始化功能的成員函數(shù)。 每當(dāng)創(chuàng)建一個對象時,就調(diào)用這個成員函數(shù),實現(xiàn)初始化。 例如: class Student { public: void init() { semeshours=100。 gpa=。 } //…… protected: int semeshours。 int gpa。 }。 void fn() { Student s。 ()。 //調(diào)用類的初始化函數(shù) //…… } 這種將初始化工作交由初始化成員函數(shù)完成的方式使系統(tǒng)多了一道處理過程,增加了書寫代碼,實現(xiàn)的機(jī)制并不理想。 另一種方法是建立對象的同時,自動調(diào)用構(gòu)造函數(shù),省去上述麻煩,使定義類對象時包含了為對象分配存儲空間和初始化的雙重任務(wù)。這種實現(xiàn)機(jī)制較為理想。 由于類的唯一性和對象的多樣性,因此 C++ 規(guī)定構(gòu)造函數(shù)與類同名。其特點是: Constructor is a function with the explicit purpose of initializing object. Because such a function constructs values of a given type, it is called a constructor. A constructor is recognized by having the same name as the class itself. When a class has a constructor, all objects of that class will be initialized by a constructor call. 構(gòu)造函數(shù)的使用方式有: 構(gòu)造函數(shù)在類體內(nèi)定義, 例如: include class Desk { public: Desk() { weight=10。 high=5。