C++11初始化变量的新方式

来源:互联网 发布:天刀捏脸最美女数据 编辑:程序博客网 时间:2024/06/05 06:23

C++提供了一种初始化变量的新方式--列表初始化(list-initialization),常用于给复杂的数据类型提供数值列表。

它使用一种{ }的方式赋值,一个重要特征是列表初始化不允许缩窄(narrowing),即变量的类型可能无法表示赋给它的值,从而导致赋值无效。

Example 1:

int h = {24}; // set h to 24int h{24};    // set h to 24int h = {};   // set h to 0int h{};      // set h to 0

Example 2:

const int code = 6; int x = 6;          char c1 {31125};    // narrowing, not allowedchar c2 = {6};      // allowed because char can hold 66char c3 {code};     // dittochar c4 = {x};      // not allowed, x is not constantx = 31325;char c5 = x;        // allowed by this form of initialization

初始化c4时,x值为6,但在编译器看来,x是一个变量,其值可能很大。编译器不会跟踪下列阶段可能发生的情况:从x被初始化到它被用来初始化c4.

原创粉丝点击