建構函式在物件建立時自動被呼叫,負責初始化成員變數、配置資源、建立類別不變式。它無回傳型別、函式名稱與類別相同、可多載。
class Counter {
public:
Counter() { m_value = 0; } // 顯式定義
private:
int m_value;
};
class Complex {
public:
Complex() : m_real(0), m_imag(0) {} // 預設
Complex(double r, double i) : m_real(r), m_imag(i) {} // 雙參數
Complex(double r) : m_real(r), m_imag(0) {} // 單參數 (亦為型別轉換建構函式)
private:
double m_real, m_imag;
};
:) 直接初始化,比進入函式體再賦值更有效率 (特別是 const/reference 成員)。class Complex {
public:
Complex(const Complex& other) : m_real(other.m_real), m_imag(other.m_imag) {}
// ...
};
const T&,用於以既有物件初始化新物件。class Buffer {
public:
Buffer(Buffer&& other) noexcept : data(other.data), size(other.size)
{
other.data = nullptr; other.size = 0; // 竊取資源
}
~Buffer() { delete[] data; }
private:
char* data;
size_t size;
};
T&& (右值參考),竊取來源物件資源,避免深拷貝開銷。noexcept 讓 STL 容器在重新配置時優先使用移動而非複製。class Complex {
public:
Complex(double r) : m_real(r), m_imag(0) {} // 允許隱式轉換: Complex c = 3.14;
// 若不想要隱式轉換,加上 explicit:
explicit Complex(double r) : m_real(r), m_imag(0) {} // 需顯式: Complex c(3.14);
// ...
};
explicit 防止非預期隱式轉換 (如函式引數隱式轉型)。Complex& operator=(const Complex& rhs)
{
if (this == &rhs) return *this; // 自我賦值檢查
m_real = rhs.m_real;
m_imag = rhs.m_imag;
return *this; // 支援鏈式賦值 a = b = c
}
| 特性 | 複製建構函式 | 賦值運算子 |
|---|---|---|
| 呼叫時機 | 新物件初始化 | 既有物件賦值 |
| 語法 | T a = b; / T a(b); | a = b; |
| 資源處理 | 直接初始化 | 需先釋放舊資源再取得新資源 |
| 回傳值 | 無 | T& (參考) |
class FileWrapper {
public:
// 1. 預設
FileWrapper() : fd(-1) {}
// 2. 一般建構 (取得擁有權)
explicit FileWrapper(const char* path) : fd(open(path, O_RDONLY)) {
if (fd < 0) throw std::runtime_error("open failed");
}
// 3. 複製建構 (深拷貝: dup 檔案描述符)
FileWrapper(const FileWrapper& other) : fd(other.fd >= 0 ? dup(other.fd) : -1) {}
// 4. 移動建構 (竊取)
FileWrapper(FileWrapper&& other) noexcept : fd(other.fd) {
other.fd = -1;
}
// 5. 複製賦值 (Copy-and-swap 慣用語)
FileWrapper& operator=(FileWrapper other) { // 以值傳遞觸發複製/移動
swap(*this, other);
return *this;
}
// 6. 移動賦值
FileWrapper& operator=(FileWrapper&& other) noexcept {
if (this != &other) {
close(fd);
fd = other.fd;
other.fd = -1;
}
return *this;
}
// 7. 解構函式
~FileWrapper() { if (fd >= 0) close(fd); }
friend void swap(FileWrapper& a, FileWrapper& b) noexcept {
std::swap(a.fd, b.fd);
}
private:
int fd;
};
explicit,除非刻意要隱式轉換。noexcept。