问题描述
第一次尝试,一切正常:
First attempt and everything works fine:
class Base {
public:
Base() {std::cout << "default ctor!\n"; }
};
...
Base b{};
Base b_one = {};
另一种实现方式(添加 explicit
) :
Another way of implementation(add explicit
):
class Base {
public:
explicit Base() {std::cout << "default ctor!\n"; }
};
...
Base b{};
Base b_one = {}; // error! Why?
我在cppreference上已经读到,在两种情况下都将使用默认初始化,并且没有差异。
I have read on cppreference that in both cases default initialization would be used and no diffences.
从列表初始化:
从值初始化:
推荐答案
不,它们是不一样的。确切地说, Base b {};
是,而 Base b_one = {};
是;对于复制列表初始化,只能调用非 explicit
构造函数。
No they're not the same. To be precise, Base b{};
is direct-list-initialization, while Base b_one = {};
is copy-list-initialization; for copy-list-initialization, only non-explicit
constructor may be called.
(强调我的意思)
复制列表初始化(考虑了显式和非显式构造函数
,但仅非显式构造函数可以称为)
copy-list-initialization (both explicit and non-explicit constructors are considered, but only non-explicit constructors may be called)
这篇关于空花括号初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!