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;
}
// ...其他成員
};
編譯器報錯:
原因:花括號初始化列表只能在數組定義時使用,定義後只能逐個元素賦值。
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;
}
#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,代碼更簡潔安全。