構(gòu)造函數(shù)是一種可初始化其類的實(shí)例的成員函數(shù)。構(gòu)造函數(shù)具有與類相同的名稱,沒(méi)有返回值。構(gòu)造函數(shù)可以具有任意數(shù)量的參數(shù),類可以具有任意數(shù)量的重載構(gòu)造函數(shù)。構(gòu)造函數(shù)可以具有任何可訪問(wèn)性(公共、受保護(hù)或私有)。如果未定義任何構(gòu)造函數(shù),則編譯器會(huì)生成不采用任何參數(shù)的默認(rèn)構(gòu)造函數(shù);可以通過(guò)將默認(rèn)構(gòu)造函數(shù)聲明為已刪除來(lái)重寫(xiě)此行為。
構(gòu)造函數(shù)順序
構(gòu)造函數(shù)按此順序執(zhí)行工作:
按聲明順序調(diào)用基類和成員構(gòu)造函數(shù)。
如果類派生自虛擬基類,則會(huì)將對(duì)象的虛擬基指針初始化。
如果類具有或繼承了虛函數(shù),則會(huì)將對(duì)象的虛函數(shù)指針初始化。虛函數(shù)指針指向類中的虛函數(shù)表,確保虛函數(shù)正確地調(diào)用綁定代碼。
它執(zhí)行自己函數(shù)體中的所有代碼。
下面的示例顯示,在派生類的構(gòu)造函數(shù)中,基類和成員構(gòu)造函數(shù)的調(diào)用順序。首先,調(diào)用基構(gòu)造函數(shù),然后按照基類成員在類聲明中出現(xiàn)的順序?qū)@些成員進(jìn)行初始化,然后,調(diào)用派生構(gòu)造函數(shù)。
#include <iostream>using namespace std;class Contained1 {public: Contained1() { cout << "Contained1 constructor." << endl; }};class Contained2 {public: Contained2() { cout << "Contained2 constructor." << endl; }};class Contained3 {public: Contained3() { cout << "Contained3 constructor." << endl; }};class BaseContainer {public: BaseContainer() { cout << "BaseContainer constructor." << endl; }private: Contained1 c1; Contained2 c2;};class DerivedContainer : public BaseContainer {public: DerivedContainer() : BaseContainer() { cout << "DerivedContainer constructor." << endl; }private: Contained3 c3;};int main() { DerivedContainer dc; int x = 3;}這是輸出:
Contained1 constructor.Contained2 constructor.BaseContainer constructor.Contained3 constructor.DerivedContainer constructor.
如果構(gòu)造函數(shù)引發(fā)異常,析構(gòu)的順序與構(gòu)造的順序相反:
構(gòu)造函數(shù)主體中的代碼將展開(kāi)。
基類和成員對(duì)象將被銷毀,順序與聲明順序相反。
如果是非委托構(gòu)造函數(shù),所有完全構(gòu)造的基類對(duì)象和成員均將被銷毀。但是,對(duì)象本身不是完全構(gòu)造的,因此析構(gòu)函數(shù)不會(huì)運(yùn)行。
成員列表
使用成員初始值設(shè)定項(xiàng)列表從構(gòu)造函數(shù)參數(shù)初始化類成員。此方法使用直接初始化,這比在構(gòu)造函數(shù)體內(nèi)使用賦值運(yùn)算符更高效。
class Box {public: Box(int width, int length, int height) : m_width(width), m_length(length), m_height(height) // member init list {} int Volume() {return m_width * m_length * m_height; }private: int m_width; int m_length; int m_height;};創(chuàng)建 Box 對(duì)象:
Box b(42, 21, 12);cout << "The volume is " << b.Volume();
顯式構(gòu)造函數(shù)
如果類具有帶一個(gè)參數(shù)的構(gòu)造函數(shù),或是如果除了一個(gè)參數(shù)之外的所有參數(shù)都具有默認(rèn)值,則參數(shù)類型可以隱式轉(zhuǎn)換為類類型。例如,如果 Box 類具有一個(gè)類似于下面這樣的構(gòu)造函數(shù):
Box(int size): m_width(size), m_length(size), m_height(size){}可以初始化 Box,如下所示:
Box b = 42;
或?qū)⒁粋€(gè) int 傳遞給采用 Box 的函數(shù):
class ShippingOrder{public: ShippingOrder(Box b, double postage) : m_box(b), m_postage(postage){}private: Box m_box; double m_postage;}//elsewhere... ShippingOrder so(42, 10.8);
這類轉(zhuǎn)換可能在某些情況下很有用,但更常見(jiàn)的是,它們可能會(huì)導(dǎo)致代碼中發(fā)生細(xì)微但嚴(yán)重的錯(cuò)誤。作為一般規(guī)則,應(yīng)對(duì)構(gòu)造函數(shù)使用 explicit 關(guān)鍵字(和用戶定義的運(yùn)算符)以防止出現(xiàn)這種隱式類型轉(zhuǎn)換:
explicit Box(int size): m_width(size), m_length(size), m_height(size){}構(gòu)造函數(shù)是顯式函數(shù)時(shí),此行會(huì)導(dǎo)致編譯器錯(cuò)誤:ShippingOrder so(42, 10.8);。
默認(rèn)構(gòu)造函數(shù)
默認(rèn)構(gòu)造函數(shù)沒(méi)有參數(shù);它們遵循略有不同的規(guī)則:
默認(rèn)構(gòu)造函數(shù)是一個(gè)特殊成員函數(shù);如果沒(méi)有在類中聲明構(gòu)造函數(shù),則編譯器會(huì)提供默認(rèn)構(gòu)造函數(shù):
class Box { Box(int width, int length, int height) : m_width(width), m_length(length), m_height(height){}};int main(){ Box box1{}; // call compiler-generated default ctor Box box2; // call compiler-generated default ctor}當(dāng)你調(diào)用默認(rèn)構(gòu)造函數(shù)并嘗試使用括號(hào)時(shí),系統(tǒng)將發(fā)出警告:
class myclass{};int main(){myclass mc(); // warning C4930: prototyped function not called (was a variable definition intended?)}這是“最棘手的解析”問(wèn)題的示例。這種示例表達(dá)式既可以解釋為函數(shù)的聲明,也可以解釋為對(duì)默認(rèn)構(gòu)造函數(shù)的調(diào)用,而且 C++ 分析器更偏向于聲明,因此表達(dá)式會(huì)被視為函數(shù)聲明。
如果聲明了任何非默認(rèn)構(gòu)造函數(shù),編譯器不會(huì)提供默認(rèn)構(gòu)造函數(shù):
class Box { Box(int width, int length, int height) : m_width(width), m_length(length), m_height(height){}};private: int m_width; int m_length; int m_height;};int main(){ Box box1(1, 2, 3); Box box2{ 2, 3, 4 }; Box box4; // compiler error C2512: no appropriate default constructor available}如果類沒(méi)有默認(rèn)構(gòu)造函數(shù),將無(wú)法通過(guò)單獨(dú)使用方括號(hào)語(yǔ)法來(lái)構(gòu)造該類的對(duì)象數(shù)組。例如,在前面提到的代碼塊中,框的數(shù)組無(wú)法進(jìn)行如下聲明:
Box boxes[3]; // compiler error C2512: no appropriate default constructor available
但是,你可以使用初始值設(shè)定項(xiàng)列表將框的數(shù)組初始化:
Box boxes[3]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };復(fù)制和移動(dòng)構(gòu)造函數(shù)
復(fù)制構(gòu)造函數(shù)是特殊成員函數(shù),它采用對(duì)相同類型對(duì)象的引用作為輸入,并創(chuàng)建它的副本。移動(dòng)也是特殊成員函數(shù)構(gòu)造函數(shù),它將現(xiàn)有對(duì)象的所有權(quán)移交給新變量,而不復(fù)制原始數(shù)據(jù)。
顯式默認(rèn)構(gòu)造函數(shù)和已刪除構(gòu)造函數(shù)
你可以顯式設(shè)置默認(rèn)復(fù)制構(gòu)造函數(shù)、設(shè)置默認(rèn)構(gòu)造函數(shù)、移動(dòng)構(gòu)造函數(shù)、復(fù)制賦值運(yùn)算符、移動(dòng)賦值運(yùn)算符和析構(gòu)函數(shù)。你可以顯式刪除所有特殊成員函數(shù)。
派生類中的構(gòu)造函數(shù)
派生類構(gòu)造函數(shù)始終調(diào)用基類構(gòu)造函數(shù),因此,在完成任何額外任務(wù)之前,它可以依賴于完全構(gòu)造的基類。調(diào)用基類構(gòu)造函數(shù)進(jìn)行派生,例如,如果 ClassA 派生自 ClassB,ClassB 派生自 ClassC,那么首先調(diào)用 ClassC 構(gòu)造函數(shù),然后調(diào)用 ClassB 構(gòu)造函數(shù),最后調(diào)用 ClassA 構(gòu)造函數(shù)。
如果基類沒(méi)有默認(rèn)構(gòu)造函數(shù),則必須在派生類構(gòu)造函數(shù)中提供基類構(gòu)造函數(shù)參數(shù):
class Box {public: Box(int width, int length, int height){ m_width = width; m_length = length; m_height = height; }private: int m_width; int m_length; int m_height;};class StorageBox : public Box {public: StorageBox(int width, int length, int height, const string label&) : Box(width, length, height){ m_label = label; }private: string m_label;};int main(){ const string aLabel = "aLabel"; StorageBox sb(1, 2, 3, aLabel);} 具有多重繼承的類的構(gòu)造函數(shù)
如果類從多個(gè)基類派生,那么將按照派生類聲明中列出的順序調(diào)用基類構(gòu)造函數(shù):
#include <iostream>using namespace std;class BaseClass1 {public: BaseClass1() { cout << "BaseClass1 constructor." << endl; }};class BaseClass2 {public: BaseClass2() { cout << "BaseClass2 constructor." << endl; }};class BaseClass3{public: BaseClass3() { cout << "BaseClass3 constructor." << endl; }};class DerivedClass : public BaseClass1, public BaseClass2, public BaseClass3 {public: DerivedClass() { cout << "DerivedClass constructor." << endl; }};int main() { DerivedClass dc;}你應(yīng)看到以下輸出:
BaseClass1 constructor.BaseClass2 constructor.BaseClass3 constructor.DerivedClass constructor.
構(gòu)造函數(shù)中的虛函數(shù)
我們建議你謹(jǐn)慎調(diào)用構(gòu)造函數(shù)中的虛函數(shù)。基類構(gòu)造函數(shù)始終在派生類構(gòu)造函數(shù)之前調(diào)用,因此基構(gòu)造函數(shù)中調(diào)用的函數(shù)是基類版本,而非派生類版本。在下面的示例中,構(gòu)造 DerivedClass 會(huì)導(dǎo)致執(zhí)行 BaseClass 的 print_it() 實(shí)現(xiàn)早于 DerivedClass 構(gòu)造函數(shù)導(dǎo)致執(zhí)行 DerivedClass 的 print_it() 實(shí)現(xiàn):
#include <iostream>using namespace std;class BaseClass{public: BaseClass(){ print_it(); } virtual void print_it() { cout << "BaseClass print_it" << endl; }};class DerivedClass : public BaseClass {public: DerivedClass() { print_it(); } virtual void print_it(){ cout << "Derived Class print_it" << endl; }};int main() { DerivedClass dc;}這是輸出:
BaseClass print_itDerived Class print_it
構(gòu)造函數(shù)和復(fù)合類
包含類類型成員的類稱為“復(fù)合類”。創(chuàng)建復(fù)合類的類類型成員時(shí),調(diào)用類自己的構(gòu)造函數(shù)之前,先調(diào)用構(gòu)造函數(shù)。當(dāng)包含的類沒(méi)有默認(rèn)構(gòu)造函數(shù)是,必須使用復(fù)合類構(gòu)造函數(shù)中的初始化列表。在之前的 StorageBox 示例中,如果將 m_label 成員變量的類型更改為新的 Label 類,則必須調(diào)用基類構(gòu)造函數(shù),并且將 m_label 變量(位于 StorageBox 構(gòu)造函數(shù)中)初始化:
class Label {public: Label(const string& name, const string& address) { m_name = name; m_address = address; } string m_name; string m_address;};class StorageBox : public Box {public: StorageBox(int width, int length, int height, Label label) : Box(width, length, height), m_label(label){}private: Label m_label;};int main(){// passing a named Label Label label1{ "some_name", "some_address" }; StorageBox sb1(1, 2, 3, label1); // passing a temporary label StorageBox sb2(3, 4, 5, Label{ "another name", "another address" }); // passing a temporary label as an initializer list StorageBox sb3(1, 2, 3, {"myname", "myaddress"});}委托構(gòu)造函數(shù)
委托構(gòu)造函數(shù)調(diào)用同一類中的其他構(gòu)造函數(shù),完成部分初始化工作。在下面的示例中,派生類具有三個(gè)構(gòu)造函數(shù),第二個(gè)構(gòu)造函數(shù)委托第一個(gè),第三個(gè)構(gòu)造函數(shù)委托第二個(gè):
#include <iostream>using namespace std;class ConstructorDestructor {public: ConstructorDestructor() { cout << "ConstructorDestructor default constructor." << endl; } ConstructorDestructor(int int1) { cout << "ConstructorDestructor constructor with 1 int." << endl; } ConstructorDestructor(int int1, int int2) : ConstructorDestructor(int1) { cout << "ConstructorDestructor constructor with 2 ints." << endl; throw exception(); } ConstructorDestructor(int int1, int int2, int int3) : ConstructorDestructor(int1, int2) { cout << "ConstructorDestructor constructor with 3 ints." << endl; } ~ConstructorDestructor() { cout << "ConstructorDestructor destructor." << endl; }};int main() { ConstructorDestructor dc(1, 2, 3);}這是輸出:
ConstructorDestructor constructor with 1 int.ConstructorDestructor constructor with 2 ints.ConstructorDestructor constructor with 3 ints.
所有構(gòu)造函數(shù)完成后,完全初始化的構(gòu)造函數(shù)將立即創(chuàng)建對(duì)象。 DerivedContainer(int int1) 成功,但是 DerivedContainer(int int1, int int2) 失敗,并調(diào)用析構(gòu)函數(shù)。
class ConstructorDestructor {public: ConstructorDestructor() { cout << "ConstructorDestructor default constructor." << endl; } ConstructorDestructor(int int1) { cout << "ConstructorDestructor constructor with 1 int." << endl; } ConstructorDestructor(int int1, int int2) : ConstructorDestructor(int1) { cout << "ConstructorDestructor constructor with 2 ints." << endl; throw exception(); } ConstructorDestructor(int int1, int int2, int int3) : ConstructorDestructor(int1, int2) { cout << "ConstructorDestructor constructor with 3 ints." << endl; } ~ConstructorDestructor() { cout << "ConstructorDestructor destructor." << endl; }};int main() { try { ConstructorDestructor cd{ 1, 2, 3 }; } catch (const exception& ex){ }}輸出:
ConstructorDestructor constructor with 1 int.ConstructorDestructor constructor with 2 ints.ConstructorDestructor destructor.
繼承構(gòu)造函數(shù) (C++11)
派生類可以使用 using 聲明從直接基類繼承構(gòu)造函數(shù),如下面的示例所示:
#include <iostream>using namespace std;class Base{public: Base() { cout << "Base()" << endl; } Base(const Base& other) { cout << "Base(Base&)" << endl; } explicit Base(int i) : num(i) { cout << "Base(int)" << endl; } explicit Base(char c) : letter(c) { cout << "Base(char)" << endl; }private: int num; char letter;};class Derived : Base{public: // Inherit all constructors from Base using Base::Base;private: // Can't initialize newMember from Base constructors. int newMember{ 0 };};int main(int argc, char argv[]){ cout << "Derived d1(5) calls: "; Derived d1(5); cout << "Derived d1('c') calls: "; Derived d2('c'); cout << "Derived d3 = d2 calls: " ; Derived d3 = d2; cout << "Derived d4 calls: "; Derived d4; // Keep console open in debug mode: cout << endl << "Press Enter to exit."; char in[1]; cin.getline(in, 1); return 0;}Derived d1(5) calls: Base(int)Derived d1('c') calls: Base(char)Derived d3 = d2 calls: Base(Base&)Derived d4 calls: Base()Press Enter to exit.using 語(yǔ)句可將來(lái)自基類的所有構(gòu)造函數(shù)引入范圍(除了簽名與派生類中的構(gòu)造函數(shù)相同的構(gòu)造函數(shù))。一般而言,當(dāng)派生類未聲明新數(shù)據(jù)成員或構(gòu)造函數(shù)時(shí),最好使用繼承構(gòu)造函數(shù)。
如果類型指定基類,則類模板可以從類型參數(shù)繼承所有構(gòu)造函數(shù):
template< typename T >class Derived : T { using T::T; // declare the constructors from T // ...};如果基類的構(gòu)造函數(shù)具有相同簽名,則派生類無(wú)法從多個(gè)基類繼承。
聲明構(gòu)造函數(shù)的規(guī)則
構(gòu)造函數(shù)與它的類的名稱相同。可以聲明任意數(shù)量的構(gòu)造函數(shù),這取決于重載函數(shù)的規(guī)則。
argument-declaration-list 可能為空。
C++ 定義兩種特殊的構(gòu)造函數(shù)(默認(rèn)構(gòu)造函數(shù)和復(fù)制構(gòu)造函數(shù)),如下表所述。

默認(rèn)構(gòu)造函數(shù)和復(fù)制構(gòu)造函數(shù)
默認(rèn)構(gòu)造函數(shù)可在沒(méi)有參數(shù)的情況下調(diào)用。但是,如果所有參數(shù)都有默認(rèn)值,則可以用參數(shù)列表聲明默認(rèn)構(gòu)造函數(shù)。同樣,復(fù)制構(gòu)造函數(shù)必須接受對(duì)相同類類型的引用的單一參數(shù)。可以提供多個(gè)參數(shù),前提是所有后續(xù)參數(shù)都有默認(rèn)值。
如果未提供任何構(gòu)造函數(shù),則編譯器將嘗試生成默認(rèn)構(gòu)造函數(shù)。如果未提供復(fù)制構(gòu)造函數(shù),則編譯器將嘗試生成一個(gè)。這些編譯器生成的構(gòu)造函數(shù)被視為公共成員函數(shù)。如果使用屬于對(duì)象但不屬于引用的第一個(gè)參數(shù)指定復(fù)制構(gòu)造函數(shù),則將生成錯(cuò)誤。
編譯器生成的默認(rèn)構(gòu)造函數(shù)將設(shè)置對(duì)象(如上文所述,初始化 vftables 和 vbtables),并調(diào)用基類和成員的默認(rèn)構(gòu)造函數(shù),但是它不執(zhí)行任何其他操作。僅當(dāng)基類和成員構(gòu)造函數(shù)存在、可訪問(wèn)并且無(wú)歧義時(shí)才會(huì)調(diào)用它們。
編譯器生成的復(fù)制構(gòu)造函數(shù)將設(shè)置新的對(duì)象,并對(duì)要復(fù)制的對(duì)象的內(nèi)容按成員復(fù)制。如果基類或成員構(gòu)造函數(shù)存在,則將調(diào)用它們;否則將執(zhí)行按位復(fù)制。
如果類 type 的所有基類和成員類均具有接受 const 參數(shù)的復(fù)制構(gòu)造函數(shù),則編譯器生成的復(fù)制構(gòu)造函數(shù)將接受 const type& 類型的單個(gè)參數(shù)。否則,編譯器生成的復(fù)制構(gòu)造函數(shù)將接受 type& 類型的單個(gè)參數(shù)。
您可以使用構(gòu)造函數(shù)初始化 const 或 volatile 對(duì)象,但是,構(gòu)造函數(shù)本身不能聲明為 const 或 volatile。構(gòu)造函數(shù)的唯一合法存儲(chǔ)類是 inline;將任何其他存儲(chǔ)類修飾符(包括 __declspec 關(guān)鍵字)與構(gòu)造函數(shù)一起使用將導(dǎo)致編譯器錯(cuò)誤。
stdcall 調(diào)用約定用于使用 __stdcall 關(guān)鍵字聲明的靜態(tài)成員函數(shù)和全局函數(shù),且不使用變量參數(shù)列表。對(duì)非靜態(tài)成員函數(shù)(如構(gòu)造函數(shù))使用 __stdcall 關(guān)鍵字時(shí),編譯器將使用 thiscall 調(diào)用約定。
基類的構(gòu)造函數(shù)不由派生類繼承。創(chuàng)建派生類類型的對(duì)象時(shí),該對(duì)象將從基類組件開(kāi)始進(jìn)行構(gòu)造;然后移到派生類組件。由于整個(gè)對(duì)象有一部分已初始化,因此編譯器使用每個(gè)基類的構(gòu)造函數(shù)(虛擬派生的情況除外,如初始化基類中所述)。
顯式調(diào)用構(gòu)造函數(shù)
可以在程序中顯式調(diào)用構(gòu)造函數(shù)來(lái)創(chuàng)建給定類型的對(duì)象。例如,若要?jiǎng)?chuàng)建描述某行末尾的兩個(gè) Point 對(duì)象,請(qǐng)編寫(xiě)以下代碼:
DrawLine( Point( 13, 22 ), Point( 87, 91 ) );
創(chuàng)建類型 Point 的兩個(gè)對(duì)象,將其傳遞給函數(shù) DrawLine,并在表達(dá)式(函數(shù)調(diào)用)的末尾將其銷毀。
在其中顯式調(diào)用構(gòu)造函數(shù)的另一個(gè)上下文正在進(jìn)行初始化:
Point pt = Point( 7, 11 );
使用接受類型為 Point 的兩個(gè)參數(shù)的構(gòu)造函數(shù)來(lái)創(chuàng)建和初始化類型為 int 的對(duì)象。
通過(guò)顯式調(diào)用構(gòu)造函數(shù)創(chuàng)建的對(duì)象(如上面的兩個(gè)示例)未進(jìn)行命名,并且該對(duì)象具有在其中創(chuàng)建它們的表達(dá)式的生存期。 臨時(shí)對(duì)象中更詳細(xì)地討論了這一點(diǎn)。
通常,從構(gòu)造函數(shù)的內(nèi)部調(diào)用所有成員函數(shù)是安全的,因?yàn)樵搶?duì)象在用戶代碼的第一行執(zhí)行之前已完全設(shè)置(已初始化虛擬表等)。但是,在構(gòu)造或析構(gòu)期間,成員函數(shù)調(diào)用抽象基類的虛擬成員函數(shù)可能是不安全的。
構(gòu)造函數(shù)可以調(diào)用虛函數(shù)。調(diào)用虛函數(shù)時(shí),調(diào)用的函數(shù)將是為構(gòu)造函數(shù)自己的類定義的函數(shù)(或從其基類繼承)。以下示例演示從構(gòu)造函數(shù)的內(nèi)部調(diào)用虛函數(shù)時(shí)發(fā)生的情況:
// specl_calling_virtual_functions.cpp// compile with: /EHsc#include <iostream>using namespace std;class Base{public: Base(); // Default constructor. virtual void f(); // Virtual member function.};Base::Base(){ cout << "Constructing Base sub-object/n"; f(); // Call virtual member function} // from inside constructor.void Base::f(){ cout << "Called Base::f()/n";}class Derived : public Base{public: Derived(); // Default constructor. void f(); // Implementation of virtual}; // function f for this class.Derived::Derived(){ cout << "Constructing Derived object/n";}void Derived::f(){ cout << "Called Derived::f()/n";}int main(){ Derived d;}在運(yùn)行前面的程序時(shí),聲明 Derived d 將產(chǎn)生以下事件序列:
調(diào)用類 Derived (Derived::Derived) 的構(gòu)造函數(shù)。
在輸入 Derived 類的構(gòu)造函數(shù)的主體之前,調(diào)用類 Base (Base::Base) 的構(gòu)造函數(shù)。
Base::Base 調(diào)用函數(shù) f,該函數(shù)是一個(gè)虛函數(shù)。通常,將調(diào)用 Derived::f,因?yàn)閷?duì)象 d 屬于類型 Derived。由于 Base::Base 函數(shù)是構(gòu)造函數(shù),因此該對(duì)象不屬于 Derived 類型,并且將調(diào)用 Base::f。
新聞熱點(diǎn)
疑難解答