初始化列表提供了初始化成員變量的方式,特別是 const、參考型別、無預設建構函數的類別成員必須在初始化列表中初始化。
#include <cstdio>
class M {
int mI;
public:
M(int i) { printf("M(%d)\n", i); mI = i; }
int getI() { return mI; }
};
class Test {
const int c; // const 必須初始化
M m1, m2; // 類別成員
public:
// 初始化列表順序決定初始化順序 (與宣告順序一致)
Test() : c(1), m1(2), m2(3) {
printf("Test()\n"); // 建構函數體內為賦值而非初始化
}
void print() { printf("c=%d, m1=%d, m2=%d\n", c, m1.getI(), m2.getI()); }
};
void run() {
Test t1;
t1.print();
}
int main() {
run();
printf("Press any key..."); getchar();
return 0;
}
M(2) // m1 先初始化 (宣告在前) M(3) // m2 再初始化 Test() // 最後執行建構函數體 c=1, m1=2, m2=3 Press any key...
物件銷毀時,析構函數執行順序與初始化順序相反:先執行 Test 析構函數體,再銷毀 m2,最後銷毀 m1。成員物件的析構函數會自動被呼叫。
const、參考、無預設建構函數的成員只能在初始化列表初始化。