不同形式的初始化 [英] Different forms of initialization

查看:138
本文介绍了不同形式的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读这本书叫做C ++的C ++之旅的Bjarne Stroustrup,里面提到基本上有两种初始化方式:

I was reading this book called 'A Tour of C++' by Bjarne Stroustrup and inside it is mentioned that there are basically two ways of initialization:


p int a = 5.2; // Stores truncated value

int a = 5.2; // Stores truncated value

int a {5.2}; //编译器抛出错误

int a{5.2}; // Compiler throws error

正如你所看到的,后一种方法更安全,更推荐。

As you can see, the latter method is safer and recommended.

但我注意到:


int a(5.2);

int a(5.2);

也有效(与第二个版本不同,它不检查类型是否匹配)。

also works (and unlike the second version, it doesn't check if the type matches).

,可以有人请解释第三种情况,我的意思是,当它应该使用,它如何与第一种情况不同。

So, can someone please explain the third case, I mean, when it should be used and how it's different than the first case.

推荐答案

当你使用int a(5.2);你正在调用int的构造函数,这是一个C ++方法来初始化变量。
这相当于其他人。
根据 http://www.cplusplus.com/doc/tutorial/variables/

When you use int a(5.2); you are calling the constructor of int, which is a C++ method to initialize variables. This is equivalent to others. According to http://www.cplusplus.com/doc/tutorial/variables/ :


在C ++中,有三种方式来初始化变量。他们都是
等价的,并且让人联想到语言在
年的演变:

In C++, there are three ways to initialize variables. They are all equivalent and are reminiscent of the evolution of the language over the years:

第一个,被称为c样初始化(因为它是从C语言继承的
),包括附加等号后跟
变量初始化的值:

The first one, known as c-like initialization (because it is inherited from the C language), consists of appending an equal sign followed by the value to which the variable is initialized:

type identifier = initial_value;例如,声明一个变量
,类型int调用x,并从它声明的同一个
初始化为零值,我们可以这样写:

type identifier = initial_value; For example, to declare a variable of type int called x and initialize it to a value of zero from the same moment it is declared, we can write:

int x = 0;

第二种方法称为构造函数初始化(由
引入C ++语言)括号之间的初始值
(()):

A second method, known as constructor initialization (introduced by the C++ language), encloses the initial value between parentheses (()):

类型标识符(initial_value);例如:

type identifier (initial_value); For example:

int x (0);

最后,第三种方法称为统一初始化,类似于上面的
,使用花括号({})而不是括号(这个
是由C ++标准的修订版在2011年引入的):

Finally, a third method, known as uniform initialization, similar to the above, but using curly braces ({}) instead of parentheses (this was introduced by the revision of the C++ standard, in 2011):

type identifier {initial_value} ;比如:

type identifier {initial_value}; For example:

int x {0};


这篇关于不同形式的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆