构造对象时C ++中括号和花括号之间的区别是什么 [英] What's the difference between parentheses and braces in c++ when constructing objects

查看:93
本文介绍了构造对象时C ++中括号和花括号之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我认为{}仅应支持 initializer_list 或数组,但是当我在代码段下运行时,我感到困惑.

  #include< iostream>使用命名空间std;结构S {int v = 0;S(int l):v(l){}};int main(){S s1(12);//statement1S s2 {12};//statement2cout<<s1.v<<恩德尔cout<<s2.v<<恩德尔} 

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

我希望 statement2 编译失败.我认为 {} 仅可用于数组或 initializer_list 类型.但是实际结果可以完美编译而不会出现错误.

我错了什么?

解决方案

对于 S ,它们具有相同的效果.两者都调用构造函数 S :: S(int)来初始化对象.

S s2 {12}; 被重新命名为列表初始化(自C ++ 11起); S 不是聚合类型,也不是 std :: initializer_list ,并且没有构造函数采用 std :: initializer_list ,然后

如果上一阶段未产生匹配,则 T 的所有构造函数都将针对由braced-init-list元素组成的参数集参与重载解析,其限制为仅允许非缩小转换.

你以为

我认为 {} 仅可用于数组或 initializer_list 类型.

这不是事实.列表初始化的效果是如果 S 是聚合类型,则执行聚合初始化;否则,将执行初始化.如果 S std :: initializer_list 的特化,则将其初始化为 std :: initializer_list ;如果 S 具有使用 std :: initializer_list 的构造函数,则首选将其用于初始化.您可以参考链接的该页面,以获取更多详细信息.

PS: S s1(12); 执行直接初始化.

What's the difference between () and {} when constructing objects?

I think {} should only support with initializer_list or an array, but when I run below snip, I confused.

#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 is right because () is the basic grammar for constructing the object.

I expect the statement2 will be compiled failed. I think {} is only can be used for an array or initializer_list type. but the actual result is compiled perfectly without error.

what do I mis?

解决方案

For S, they have the same effect. Both invoke the constructor S::S(int) to initialize the objects.

S s2{12}; is regared as list initialization (since C++11); S is not an aggregate type and not std::initializer_list, and has no constructor taking std::initializer_list, then

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.

and you thought that

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

This is not true. The effect of list-initialization is that, e.g. if S is an aggregate type, then aggregate initialization is performed; if S is a specialization of std::initializer_list, then it's initialized as a std::initializer_list; if S has a constructor taking std::initializer_list, then it will be preferred to be used for initialization. You can refer to the page linked for more precise details.

PS: S s1(12); performs direct initialization.

这篇关于构造对象时C ++中括号和花括号之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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