萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ 類別建構函式完整解析:五大類型與實務範例

建構函式核心概念

建構函式在物件建立時自動被呼叫,負責初始化成員變數、配置資源、建立類別不變式。它無回傳型別、函式名稱與類別相同、可多載。

五大建構函式類型

1. 預設建構函式

class Counter {
public:
    Counter() { m_value = 0; } // 顯式定義
private:
    int m_value;
};
  • 若類別未宣告任何建構函式,編譯器會隱式產生一個「不做任何事」的預設建構函式。
  • 一旦自訂任何建構函式,隱式預設建構函式不再產生,需自行提供。

2. 一般/多載建構函式

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 成員)。

3. 複製建構函式

class Complex {
public:
    Complex(const Complex& other) : m_real(other.m_real), m_imag(other.m_imag) {}
    // ...
};
  • 參數為 const T&,用於以既有物件初始化新物件。
  • 隱式複製建構函式執行淺拷貝 (逐位元複製),若類別含指標/資源控制代碼會導致雙重釋放或資源洩漏 → 必須實作深拷貝。

4. 移動建構函式 (C++11)

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 容器在重新配置時優先使用移動而非複製。

5. 型別轉換建構函式

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 防止非預期隱式轉換 (如函式引數隱式轉型)。

賦值運算子 vs 複製建構函式

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& (參考)

實務範例:資源管理類別 (Rule of Five)

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;
};

最佳實踐總結

  1. 優先使用成員初始化列。
  2. 管理資源的類別必須實作Rule of Five (或 Rule of Zero:改用智慧指標/容器)。
  3. 單參數建構函式預設加 explicit,除非刻意要隱式轉換。
  4. 移動操作標記 noexcept。
  5. 複製賦值採用 Copy-and-swap 慣用語,確保強烈例外安全。
copyright © 萬盛學電腦網 all rights reserved