什么是就地初始化
在C++03标准中,只有静态常量整型成员才能在类中就地初始化
class X {
static const int a = 7; // ok
const int b = 7; // 错误: 非 static
static int c = 7; // 错误: 非 const
static const string d = "odd"; // 错误: 非整型
};
C++11标准中,非静态成员可以在它声明的时候初始化
“就地初始化”的术语的来源有多处:
(1) 就地初始化:《深入理解C++11》
(2) In-class initializer : https://isocpp.org/
(3) default member initializer : https://cppreference.com
例子和规则
class S {
int m = 7; // ok, copy-initializes m
int n(7); // 错误:不允许用小括号初始化
std::string s{'a', 'b', 'c'}; // ok, direct list-initializes s
std::string t{"Constructor run"}; // ok
int a[] = {1,2,3}; // 错误:数组类型成员不能自动推断大小
int b[3] = {1,2,3}; // ok
// 引用类型的成员有一些额外限制,参考标准
public:
S() { }
};