{ } 和等号变量的区别 [英] difference between { } and equal sign variables

查看:36
本文介绍了{ } 和等号变量的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C++ 编程有点陌生.我在谷歌的任何地方都找不到我的答案,所以希望它可以在这里得到解答.

I'm somewhat new to c++ programming. I couldn't find my answer any where on google so hopefully it can be answered here.

以下有区别吗

unsigned int counter{ 1 };

unsigned int counter = 1;

这本书使用了第一个选项,这让我感到困惑,因为它没有解释差异.以下是我正在关注的书中的以下代码.

the book uses the first option and its confusing to me because it doesn't explain the difference. below is the following code from the book i'm following.

#include <iostream>
#include <iomanip>
#include <cstdlib> // contains function prototype for rand()
using namespace std;

int main()
{
    for (unsigned int counter{ 1 }; counter <= 20; ++counter) {
        cout << setw(10) << (1 + rand() % 6);

        // if counter is divisible by 5, start a new line of output
        if (counter % 5 == 0) {
            cout << endl;
        }
    }

}

推荐答案

是的,它们是 C++ 中两种不同类型的初始化.

Yes, they are two different types of initialization in C++.

而第二个,即 unsigned int counter = 1;,是一个 复制初始化.

Whereas, the second one, i.e., unsigned int counter = 1;, is a copy initialization.

有关所有详细信息,您可以直接参考文档.

For all the details you can directly refer to the documentation.

但是,我可以强调:

复制初始化比直接初始化更宽松:显式构造函数不会转换构造函数,也不考虑进行复制初始化.

Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.

此处的初始化参考

对于 unsigned int 类型(例如在您的情况下),两种初始化之间没有真正的区别.

For unsigned int type (such in your case), there are no real differences between the two initializations.

注意在第一条语句 (unsigned int counter{ 1 }) 中使用大括号提供了额外的约束:

Note The usage of curly braces in the first statement (unsigned int counter{ 1 }) provides an additional constraint:

否则(如果 T 不是类类型),如果花括号初始化列表只有一个元素 [...],T 是直接初始化[...],除了不允许缩小转换.

Otherwise (if T is not a class type), if the braced-init-list has only one element [...], T is direct-initialized [...], except that narrowing conversions are not allowed.

换句话说,在初始化中使用大括号不允许数据松散.

In other words, the usage of curly braces in the initialization does not allow data looseness.

即:

unsigned int counter{ 12.3 };  // error!!!

无法编译,因为您试图用浮点值初始化整数.

won't compile because you are trying to initialize an integer with a floating-point value.

注意这是初始化中花括号的属性".与初始化类型没有严格的关系.

Note this is a "property" of curly braces in the initialization. It is not strictly related to the initialization type.

其实你也可以这样写:

unsigned int counter = { 12.3 };  // error!

相反,它是一个复制初始化,但花括号不允许缩小转换.

which is, instead, a copy initialization, but having curly braces does not allows narrowing conversions.

这篇关于{ } 和等号变量的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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