统一初始化
after C++11用 {}代替 ()对变量进行初始化使用,这被称为统一初始化(uniform initialization)。
int values[] { 1, 2, 3 };
std::vector<int> v { 2, 3, 5, 7, 11, 13, 17 };
std::vector<std::string> cities {"Berlin", "New York", "London", "Braunschweig", "Cairo", "Cologne"};
重点:实现一个接收std::initializer_list的构造函数
template< class T >
class initializer_list;
void print (std::initializer_list<int> vals)
{
for (auto p=vals.begin(); p!=vals.end(); ++p)
{
std::cout << *p << "\n";
}
}
特点:
(1)禁止内置类型之间的隐式缩小转换
double x, y, z;
int sum1{ x + y + z }; // error! sum of doubles may not be expressible as int
(2)当一个构造函数没有标成 explicit 时,你可以使用大括号不写类名来进行构造,如果调用上下文要求那类对象的话。如:
Obj getObj()
{
return {1.0};
}
(3) 编译器优先将“{}”初始化与与std :: initializer_list的构造函数进行匹配
class Widget {
public:
Widget(int i, bool b); // as before
Widget(int i, double d); // as before
Widget(std::initializer_list<bool> il); // element type is
// now bool
… // no implicit
}; // conversion funcs
Widget w{10, 5.0}; // error! requires narrowing conversions
类数据成员的默认初始化
C++11 允许在声明数据成员时直接给予一个初始化表达式
before C++11
class Complex {
public:
Complex()
: re_(0) , im_(0) {}
Complex(float re)
: re_(re), im_(0) {}
Complex(float re, float im)
: re_(re) , im_(im) {}
…
private:
float re_;
float im_;
};
after C++11
class Complex {
public:
Complex() {}
Complex(float re) : re_(re) {}
Complex(float re, float im)
: re_(re) , im_(im) {}
private:
float re_{0};
float im_{0};
};