gpt4 book ai didi

c++ - 构造函数中的 std::initializer_list 转换

转载 作者:行者123 更新时间:2023-11-30 05:25:44 25 4
gpt4 key购买 nike

我是 C++11 的新手,我想知道这段代码在内部是如何工作的:

class MyClass
{
public:
MyClass(int a, double b) {
cout << "ctor()" << endl;
}
};

int main()
{
MyClass i1{4, 7};
return 0;
}

我对new initializer list的理解是,它是一个类std::initializer_list,通过代码中的特殊语法{ .... }构造出来的。那么,由 {4, 7} 创建的这个类实例如何在内部转换为适合 MyClass 的构造函数的形式?谢谢。

最佳答案

我想事情就是这样发生的。摘自:Explanation of list initialization at cppreference.com

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. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all)

关于c++ - 构造函数中的 std::initializer_list 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38114652/

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