gpt4 book ai didi

c++ - c++构造对象时圆括号和大括号有什么区别

转载 作者:行者123 更新时间:2023-11-30 00:42:56 28 4
gpt4 key购买 nike

(){} 在构造对象时有什么区别?

我认为 {} 应该只支持 initializer_list 或数组,但是当我在 snip 下面运行时,我感到困惑。

#include <iostream>
using namespace std;
struct S {
int v=0;
S(int l) : v(l) {
}
};


int main()
{
S s1(12); // statement1
S s2{12}; // statement2
cout << s1.v << endl;
cout << s2.v << endl;
}

statement1 是对的,因为 () 是构造对象的基本语法。

我预计 statement2 会编译失败。我认为 {} 只能用于数组或 initializer_list 类型。但实际结果编译完美无误。

我错了什么?

最佳答案

对于S,它们的作用是一样的。两者都调用构造函数 S::S(int) 来初始化对象。

S s2{12}; 被视为 list initialization (C++11 起); S 不是聚合类型,也不是 std::initializer_list,并且没有采用 std::initializer_list 的构造函数,则

If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed.

你是这么想的

I think {} is only can be used for an array or initializer_list type.

这不是真的。列表初始化的效果是,例如如果 S 是聚合类型,则执行聚合初始化;如果 Sstd::initializer_list 的特化,则它被初始化为 std::initializer_list;如果 S 有一个采用 std::initializer_list 的构造函数,那么它将优先用于初始化。可以引用the page链接以获取更精确的详细信息。

PS: S s1(12); 执行 direct initialization .

关于c++ - c++构造对象时圆括号和大括号有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57304873/

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