首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 類私有成員數組在構造函數中初始化的正確姿勢

     編輯:程式設計綜合問答

錯誤代碼示例

class Base {
private:
    int r[MAX_SIZE];
    int length;
public:
    Base() {
        r[MAX_SIZE] = {1,2,0,5,8,9,7,3,6,4}; // 編譯錯誤
        length = 10;
    }
    // ...其他成員
};

錯誤分析

編譯器報錯:

  1. 警告:extended initializer lists 僅在 C++11 (-std=c++0x) 下可用
  2. 錯誤:不能將初始化列表轉換為 int 進行賦值

原因:花括號初始化列表只能在數組定義時使用,定義後只能逐個元素賦值。

正確解決方案

方案一:C++11 列表初始化(推薦)

class Base {
private:
    int r[MAX_SIZE] = {1,2,0,5,8,9,7,3,6,4}; // 類內初始化
    int length = 10;
public:
    Base() = default;
    // ...
};

方案二:構造函數中循環賦值

Base() {
    int init[] = {1,2,0,5,8,9,7,3,6,4};
    for (int i = 0; i < 10; ++i) {
        r[i] = init[i];
    }
    length = 10;
}

方案三:使用 std::array(現代 C++ 最佳實踐)

#include <array>
class Base {
private:
    std::array<int, MAX_SIZE> r = {1,2,0,5,8,9,7,3,6,4};
    int length = 10;
public:
    Base() = default;
    // ...
};

總結

避免在構造函數體中直接對已定義的數組使用初始化列表賦值。優先使用 C++11 類內初始化或 std::array,代碼更簡潔安全。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved