【1】默認構造函數
關於默認構造函數,請參見隨筆《類中函數》
請看測試代碼:
1 #include <iostream>
2 using namespace std; 3
4 // 空類
5 class empty 6 { 7 }; 8
9 // 一個默認構造函數,一個自定義構造函數
10 class Base 11 { 12 public: 13 Base() 14 { 15 cout << " default Base construct " << endl; 16 m_nValue = 100; 17 }; 18 Base(int nValue) 19 { 20 cout << " custom Base construct " << endl; 21 m_nValue = nValue; 22 }; 23
24 private: 25 int m_nValue; 26 }; 27
28 // 一個復合默認構造函數
29 class custom 30 { 31 public: 32 custom(int value = 100) 33 { 34 cout << " default && custom construct " << endl; 35 m_nValue = value; 36 } 37
38 private: 39 int m_nValue; 40 }; 41
42 void main() 43 { 44 empty* pEmpty1 = new empty; 45 empty* pEmpty2 = new empty(); 46
47 Base* pBase1 = new Base; 48 Base* pBase2 = new Base(); 49 Base* pBase3 = new Base(200); 50
51 custom* pCustom1 = new custom; 52 custom* pCustom2 = new custom(); 53
54 delete pEmpty1; 55 delete pEmpty2; 56
57 delete pBase1; 58 delete pBase2; 59 delete pBase3; 60
61 delete pCustom1; 62 delete pCustom2; 63 } 64 // Result:
65 /*
66 default Base construct 67 default Base construct 68 custom Base construct 69 default && custom construct 70 default && custom construct 71 */
至此足以。
【2】加括號與不加的區別
(1)加括號
1. 若括號為空,即無實參項,那么理解為調用默認構造函數;
2. 若括號非空,即有實參項,可以理解為調用重載構造函數,或復合默認構造函數。
(2)不加括號
調用默認構造函數,或復合默認構造函數。
【3】默認構造函數 與 復合默認構造函數的區別
默認構造函數:編譯器會為每一個類默認提供一個構造函數,稱之為默認構造函數。默認構造函數一般參數為空。
復合默認構造函數:一個由用戶自定義的所有形式參數都賦有默認值的構造函數,稱之為復合默認構造函數。
兩者聯系:
一個類中,若一旦有一個用戶自定義構造函數,那么由編譯器提供的默認構造函數就不再存在。用戶自定義的構造函數為默認構造函數的重載版。
默認構造函數不復存在時,用戶必須為這個類再自定義一個復合默認構造函數(選所有自定義構造函數其中之一,把形式參數均賦默認值即可)。
不論自定義構造函數(即構造函數的重載版)有多少個,只允許有一個復合默認構造函數。
Good Good Study, Day Day Up.
順序 選擇 循環 總結