完全掌握C++編程中構(gòu)造函數(shù)使用的超級學(xué)習(xí)教程
構(gòu)造函數(shù)是一種可初始化其類的實例的成員函數(shù)。構(gòu)造函數(shù)具有與類相同的名稱,沒有返回值。構(gòu)造函數(shù)可以具有任意數(shù)量的參數(shù),類可以具有任意數(shù)量的重載構(gòu)造函數(shù)。構(gòu)造函數(shù)可以具有任何可訪問性(公共、受保護或私有)。如果未定義任何構(gòu)造函數(shù),則編譯器會生成不采用任何參數(shù)的默認構(gòu)造函數(shù);可以通過將默認構(gòu)造函數(shù)聲明為已刪除來重寫此行為。
構(gòu)造函數(shù)順序
構(gòu)造函數(shù)按此順序執(zhí)行工作:
按聲明順序調(diào)用基類和成員構(gòu)造函數(shù)。
如果類派生自虛擬基類,則會將對象的虛擬基指針初始化。
如果類具有或繼承了虛函數(shù),則會將對象的虛函數(shù)指針初始化。虛函數(shù)指針指向類中的虛函數(shù)表,確保虛函數(shù)正確地調(diào)用綁定代碼。
它執(zhí)行自己函數(shù)體中的所有代碼。
下面的示例顯示,在派生類的構(gòu)造函數(shù)中,基類和成員構(gòu)造函數(shù)的調(diào)用順序。首先,調(diào)用基構(gòu)造函數(shù),然后按照基類成員在類聲明中出現(xiàn)的順序?qū)@些成員進行初始化,然后,調(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ù)主體中的代碼將展開。
基類和成員對象將被銷毀,順序與聲明順序相反。
如果是非委托構(gòu)造函數(shù),所有完全構(gòu)造的基類對象和成員均將被銷毀。但是,對象本身不是完全構(gòu)造的,因此析構(gòu)函數(shù)不會運行。
成員列表
使用成員初始值設(shè)定項列表從構(gòu)造函數(shù)參數(shù)初始化類成員。此方法使用直接初始化,這比在構(gòu)造函數(shù)體內(nèi)使用賦值運算符更高效。
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 對象:
Box b(42, 21, 12); cout << "The volume is " << b.Volume();
顯式構(gòu)造函數(shù)
如果類具有帶一個參數(shù)的構(gòu)造函數(shù),或是如果除了一個參數(shù)之外的所有參數(shù)都具有默認值,則參數(shù)類型可以隱式轉(zhuǎn)換為類類型。例如,如果 Box 類具有一個類似于下面這樣的構(gòu)造函數(shù):
Box(int size): m_width(size), m_length(size), m_height(size){}
可以初始化 Box,如下所示:
Box b = 42;
或?qū)⒁粋€ 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)換可能在某些情況下很有用,但更常見的是,它們可能會導(dǎo)致代碼中發(fā)生細微但嚴(yán)重的錯誤。作為一般規(guī)則,應(yīng)對構(gòu)造函數(shù)使用 explicit 關(guān)鍵字(和用戶定義的運算符)以防止出現(xiàn)這種隱式類型轉(zhuǎn)換:
explicit Box(int size): m_width(size), m_length(size), m_height(size){}
構(gòu)造函數(shù)是顯式函數(shù)時,此行會導(dǎo)致編譯器錯誤:ShippingOrder so(42, 10.8);。
默認構(gòu)造函數(shù)
默認構(gòu)造函數(shù)沒有參數(shù);它們遵循略有不同的規(guī)則:
默認構(gòu)造函數(shù)是一個特殊成員函數(shù);如果沒有在類中聲明構(gòu)造函數(shù),則編譯器會提供默認構(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)用默認構(gòu)造函數(shù)并嘗試使用括號時,系統(tǒng)將發(fā)出警告:
class myclass{}; int main(){ myclass mc(); // warning C4930: prototyped function not called (was a variable definition intended?) }
這是“最棘手的解析”問題的示例。這種示例表達式既可以解釋為函數(shù)的聲明,也可以解釋為對默認構(gòu)造函數(shù)的調(diào)用,而且 C++ 分析器更偏向于聲明,因此表達式會被視為函數(shù)聲明。
如果聲明了任何非默認構(gòu)造函數(shù),編譯器不會提供默認構(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 }
如果類沒有默認構(gòu)造函數(shù),將無法通過單獨使用方括號語法來構(gòu)造該類的對象數(shù)組。例如,在前面提到的代碼塊中,框的數(shù)組無法進行如下聲明:
Box boxes[3]; // compiler error C2512: no appropriate default constructor available
但是,你可以使用初始值設(shè)定項列表將框的數(shù)組初始化:
Box boxes[3]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
復(fù)制和移動構(gòu)造函數(shù)
復(fù)制構(gòu)造函數(shù)是特殊成員函數(shù),它采用對相同類型對象的引用作為輸入,并創(chuàng)建它的副本。移動也是特殊成員函數(shù)構(gòu)造函數(shù),它將現(xiàn)有對象的所有權(quán)移交給新變量,而不復(fù)制原始數(shù)據(jù)。
顯式默認構(gòu)造函數(shù)和已刪除構(gòu)造函數(shù)
你可以顯式設(shè)置默認復(fù)制構(gòu)造函數(shù)、設(shè)置默認構(gòu)造函數(shù)、移動構(gòu)造函數(shù)、復(fù)制賦值運算符、移動賦值運算符和析構(gòu)函數(shù)。你可以顯式刪除所有特殊成員函數(shù)。
派生類中的構(gòu)造函數(shù)
派生類構(gòu)造函數(shù)始終調(diào)用基類構(gòu)造函數(shù),因此,在完成任何額外任務(wù)之前,它可以依賴于完全構(gòu)造的基類。調(diào)用基類構(gòu)造函數(shù)進行派生,例如,如果 ClassA 派生自 ClassB,ClassB 派生自 ClassC,那么首先調(diào)用 ClassC 構(gòu)造函數(shù),然后調(diào)用 ClassB 構(gòu)造函數(shù),最后調(diào)用 ClassA 構(gòu)造函數(shù)。
如果基類沒有默認構(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ù)
如果類從多個基類派生,那么將按照派生類聲明中列出的順序調(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 會導(dǎo)致執(zhí)行 BaseClass 的 print_it() 實現(xiàn)早于 DerivedClass 構(gòu)造函數(shù)導(dǎo)致執(zhí)行 DerivedClass 的 print_it() 實現(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_it Derived Class print_it
構(gòu)造函數(shù)和復(fù)合類
包含類類型成員的類稱為“復(fù)合類”。創(chuàng)建復(fù)合類的類類型成員時,調(diào)用類自己的構(gòu)造函數(shù)之前,先調(diào)用構(gòu)造函數(shù)。當(dāng)包含的類沒有默認構(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òu)造函數(shù),第二個構(gòu)造函數(shù)委托第一個,第三個構(gòu)造函數(shù)委托第二個:
#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)建對象。 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 語句可將來自基類的所有構(gòu)造函數(shù)引入范圍(除了簽名與派生類中的構(gòu)造函數(shù)相同的構(gòu)造函數(shù))。一般而言,當(dāng)派生類未聲明新數(shù)據(jù)成員或構(gòu)造函數(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ù)具有相同簽名,則派生類無法從多個基類繼承。
聲明構(gòu)造函數(shù)的規(guī)則
構(gòu)造函數(shù)與它的類的名稱相同。可以聲明任意數(shù)量的構(gòu)造函數(shù),這取決于重載函數(shù)的規(guī)則。
argument-declaration-list 可能為空。
C++ 定義兩種特殊的構(gòu)造函數(shù)(默認構(gòu)造函數(shù)和復(fù)制構(gòu)造函數(shù)),如下表所述。
默認構(gòu)造函數(shù)和復(fù)制構(gòu)造函數(shù)
默認構(gòu)造函數(shù)可在沒有參數(shù)的情況下調(diào)用。但是,如果所有參數(shù)都有默認值,則可以用參數(shù)列表聲明默認構(gòu)造函數(shù)。同樣,復(fù)制構(gòu)造函數(shù)必須接受對相同類類型的引用的單一參數(shù)??梢蕴峁┒鄠€參數(shù),前提是所有后續(xù)參數(shù)都有默認值。
如果未提供任何構(gòu)造函數(shù),則編譯器將嘗試生成默認構(gòu)造函數(shù)。如果未提供復(fù)制構(gòu)造函數(shù),則編譯器將嘗試生成一個。這些編譯器生成的構(gòu)造函數(shù)被視為公共成員函數(shù)。如果使用屬于對象但不屬于引用的第一個參數(shù)指定復(fù)制構(gòu)造函數(shù),則將生成錯誤。
編譯器生成的默認構(gòu)造函數(shù)將設(shè)置對象(如上文所述,初始化 vftables 和 vbtables),并調(diào)用基類和成員的默認構(gòu)造函數(shù),但是它不執(zhí)行任何其他操作。僅當(dāng)基類和成員構(gòu)造函數(shù)存在、可訪問并且無歧義時才會調(diào)用它們。
編譯器生成的復(fù)制構(gòu)造函數(shù)將設(shè)置新的對象,并對要復(fù)制的對象的內(nèi)容按成員復(fù)制。如果基類或成員構(gòu)造函數(shù)存在,則將調(diào)用它們;否則將執(zhí)行按位復(fù)制。
如果類 type 的所有基類和成員類均具有接受 const 參數(shù)的復(fù)制構(gòu)造函數(shù),則編譯器生成的復(fù)制構(gòu)造函數(shù)將接受 const type& 類型的單個參數(shù)。否則,編譯器生成的復(fù)制構(gòu)造函數(shù)將接受 type& 類型的單個參數(shù)。
您可以使用構(gòu)造函數(shù)初始化 const 或 volatile 對象,但是,構(gòu)造函數(shù)本身不能聲明為 const 或 volatile。構(gòu)造函數(shù)的唯一合法存儲類是 inline;將任何其他存儲類修飾符(包括 __declspec 關(guān)鍵字)與構(gòu)造函數(shù)一起使用將導(dǎo)致編譯器錯誤。
stdcall 調(diào)用約定用于使用 __stdcall 關(guān)鍵字聲明的靜態(tài)成員函數(shù)和全局函數(shù),且不使用變量參數(shù)列表。對非靜態(tài)成員函數(shù)(如構(gòu)造函數(shù))使用 __stdcall 關(guān)鍵字時,編譯器將使用 thiscall 調(diào)用約定。
基類的構(gòu)造函數(shù)不由派生類繼承。創(chuàng)建派生類類型的對象時,該對象將從基類組件開始進行構(gòu)造;然后移到派生類組件。由于整個對象有一部分已初始化,因此編譯器使用每個基類的構(gòu)造函數(shù)(虛擬派生的情況除外,如初始化基類中所述)。
顯式調(diào)用構(gòu)造函數(shù)
可以在程序中顯式調(diào)用構(gòu)造函數(shù)來創(chuàng)建給定類型的對象。例如,若要創(chuàng)建描述某行末尾的兩個 Point 對象,請編寫以下代碼:
DrawLine( Point( 13, 22 ), Point( 87, 91 ) );
創(chuàng)建類型 Point 的兩個對象,將其傳遞給函數(shù) DrawLine,并在表達式(函數(shù)調(diào)用)的末尾將其銷毀。
在其中顯式調(diào)用構(gòu)造函數(shù)的另一個上下文正在進行初始化:
Point pt = Point( 7, 11 );
使用接受類型為 Point 的兩個參數(shù)的構(gòu)造函數(shù)來創(chuàng)建和初始化類型為 int 的對象。
通過顯式調(diào)用構(gòu)造函數(shù)創(chuàng)建的對象(如上面的兩個示例)未進行命名,并且該對象具有在其中創(chuàng)建它們的表達式的生存期。 臨時對象中更詳細地討論了這一點。
通常,從構(gòu)造函數(shù)的內(nèi)部調(diào)用所有成員函數(shù)是安全的,因為該對象在用戶代碼的第一行執(zhí)行之前已完全設(shè)置(已初始化虛擬表等)。但是,在構(gòu)造或析構(gòu)期間,成員函數(shù)調(diào)用抽象基類的虛擬成員函數(shù)可能是不安全的。
構(gòu)造函數(shù)可以調(diào)用虛函數(shù)。調(diào)用虛函數(shù)時,調(diào)用的函數(shù)將是為構(gòu)造函數(shù)自己的類定義的函數(shù)(或從其基類繼承)。以下示例演示從構(gòu)造函數(shù)的內(nèi)部調(diào)用虛函數(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; }
在運行前面的程序時,聲明 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ù)是一個虛函數(shù)。通常,將調(diào)用 Derived::f,因為對象 d 屬于類型 Derived。由于 Base::Base 函數(shù)是構(gòu)造函數(shù),因此該對象不屬于 Derived 類型,并且將調(diào)用 Base::f。
相關(guān)文章
C++用new創(chuàng)建對象和不用new創(chuàng)建對象的區(qū)別解析
在C++用new創(chuàng)建對象和不用new創(chuàng)建對象是有區(qū)別的,不知你是否清楚的了解它們到底有什么樣的區(qū)別呢?下面小編就用示例來告訴大家吧,需要的朋友可以過來參考下2013-07-07C語言數(shù)據(jù)結(jié)構(gòu)之堆排序的優(yōu)化算法
堆排序Heap?Sort就是利用堆進行排序的方法,下面這篇文章主要給大家介紹了關(guān)于C語言數(shù)據(jù)結(jié)構(gòu)之堆排序的優(yōu)化算法的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-04-04詳解C++ 參數(shù)的三種傳遞方式和應(yīng)用場景
這篇文章主要介紹C++ 參數(shù)的三種傳遞方式和應(yīng)用場景,C++ 參數(shù)的三種傳遞方式分別是值傳遞、指針傳遞和引用傳遞,感興趣的同學(xué)可以參考閱讀下2023-06-06