void 也不行)。this 指標 (指向新建物件)。
class F {
int mx, my, mi, mj;
public:
F(int x, int y);
};
// 寫法 1:初始化列表 (推薦)
F::F(int x, int y) : mx(x), my(y) {
mi = 0; mj = 0; // 指派
}
// 寫法 2:函式本體指派
F::F(int x, int y) {
mx = x; my = y; mi = 0; mj = 0;
}
class B : public A {
public:
B(int x, int y) : A(x) {} // 傳遞參數給基類
};
const 資料成員只能在初始化列表初始化,函式本體無法指派。
class ConstDemo {
const int id;
public:
ConstDemo(int i) : id(i) {} // 正確
// ConstDemo(int i) { id = i; } // 編譯錯誤
};
const,必須初始化列表綁定。
最佳實務:初始化列表書寫順序與成員宣告順序保持一致,避免隱性順序差異導致難以診斷的 Bug。
class FileHandle {
FILE* fp;
public:
FileHandle(const char* path, const char* mode) : fp(fopen(path, mode)) {
if (!fp) throw std::runtime_error("Open failed");
}
~FileHandle() { if (fp) fclose(fp); }
// 禁用拷貝,支援移動
FileHandle(const FileHandle&) = delete;
FileHandle& operator=(const FileHandle&) = delete;
FileHandle(FileHandle&& other) noexcept : fp(other.fp) { other.fp = nullptr; }
};
class Date {
int y, m, d;
public:
Date(int y, int m, int d) : y(y), m(m), d(d) { validate(); }
Date() : Date(1970, 1, 1) {} // 委派給主建構函式
Date(const std::string& s) : Date() { parse(s); }
};
const/參考/無預設建構成員是否在初始化列表初始化?