C ++ 11变量初始化和声明 [英] C++11 Variable Initialization and Declaration
问题描述
使用C ++ 11提供了一种新的方法来初始化和声明变量。
原始
int c_derived = 0;
C ++ 11
int modern {0};
每种方法的优点和缺点是什么?为什么要实现一个新的方法?
你错了 - int modern
在C ++中,可以在C ++的旧版本中使用表单(带圆括号) +11,新表单使用大括号来提供统一的初始化,所以你说
int modern {0};
这种新表单的主要优点是它可以一直使用到处。它清楚地表明,您正在初始化一个新对象,而不是调用函数,或者更糟糕的是,声明一个。 / p>
它还提供了与C风格(聚合)结构初始化的语法一致性,形式如下:
struct A
{
int a; int b;
};
A a = {1,2};
对于缩小数值类型的转换,还有更严格的规则
With C++11 came a new way to initialize and declare variables.
Original
int c_derived = 0;
C++11
int modern{0};
What are the pros and cons of each method, if there are any? Why implement a new method? Does the compiler do anything different?
You're mistaken -- the int modern(0)
form (with round brackets) was available in older versions of C++, and continues to be available in C++11.
In C++11, the new form uses curly brackets to provide uniform initialisation, so you say
int modern{0};
The main advantage of this new form is that it can be consistently used everywhere. It makes it clear that you're initialising a new object, rather than calling a function or, worse, declaring one.
It also provides syntactical consistency with C-style ("aggregate") struct initialisation, of the form
struct A
{
int a; int b;
};
A a = { 1, 2 };
There are also more strict rules with regard to narrowing conversions of numeric types when the curly-bracket form is used.
这篇关于C ++ 11变量初始化和声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!