将聚合初始化为 class 成员
Initialize aggregate as class member
在此代码中:
#include <array>
#include <cstdint>
struct K {
std::array<char, 4> a;
std::uint8_t b;
};
const K k1 = { {'T', 'e', 's', 't'}, 1 };
class X {
const K k2 = { {'A', 'b', 'c', 'd'}, 2 };
};
我可以初始化一个全局对象k1
就好了。但是尝试在 class 成员 k2
的默认初始值设定项上使用相同的语法会产生编译器错误(来自 g++-4.8.2 和 g++-5.2.0 的类似错误):
main.cpp:12:44: error: array must be initialized with a brace-enclosed initializer
const K k2 = { {'A', 'b', 'c', 'd'}, 2 };
^
main.cpp:12:44: error: too many initializers for 'std::array<char, 4ul>'
在声明时初始化 k2
的正确方法是什么?
您只需要一副额外的牙套:
class X {
const K k2 = { {{'A', 'b', 'c', 'd'}}, 2 };
};
在此代码中:
#include <array>
#include <cstdint>
struct K {
std::array<char, 4> a;
std::uint8_t b;
};
const K k1 = { {'T', 'e', 's', 't'}, 1 };
class X {
const K k2 = { {'A', 'b', 'c', 'd'}, 2 };
};
我可以初始化一个全局对象k1
就好了。但是尝试在 class 成员 k2
的默认初始值设定项上使用相同的语法会产生编译器错误(来自 g++-4.8.2 和 g++-5.2.0 的类似错误):
main.cpp:12:44: error: array must be initialized with a brace-enclosed initializer
const K k2 = { {'A', 'b', 'c', 'd'}, 2 };
^
main.cpp:12:44: error: too many initializers for 'std::array<char, 4ul>'
在声明时初始化 k2
的正确方法是什么?
您只需要一副额外的牙套:
class X {
const K k2 = { {{'A', 'b', 'c', 'd'}}, 2 };
};