gpt4 book ai didi

c++ - { } 和等号变量之间的区别

转载 作者:行者123 更新时间:2023-12-02 20:45:39 24 4
gpt4 key购买 nike

我对 C++ 编程有点陌生。我在谷歌上找不到我的答案,所以希望可以在这里得到答案。

以下有什么区别

unsigned int counter{ 1 };

unsigned int counter = 1;

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

#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++ 中两种不同类型的初始化。

有关所有详细信息,您可以直接引用文档。

但是,我可以强调:

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

Initialization references here

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

<小时/>

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

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.

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

即:

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

无法编译,因为您正在尝试用浮点值初始化整数。

请注意,这是初始化中大括号的“属性”。 与初始化类型没有严格关系

其实你也可以这样写:

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

这是一个复制初始化,但使用大括号不允许缩小转换。

关于c++ - { } 和等号变量之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58010112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com