C++
我读过没有explicit
关键字和一个参数的构造函数(或对具有多个参数的 ctor 的单参数调用,其中除了一个以外的所有参数都具有默认值)可以执行一次隐式转换。给定两个类,其中Foo
的 ctor 有两个 int
参数,而Bar
' 的 ctor 有两个 Foo
参数,该语句似乎暗示Bar
使用两个不合格的 s 集调用 's ctorint
不应转换为Bar
使用两个 ' 调用 's ctor Foo
。那么,为什么下面会编译呢?
struct Foo {
Foo(int x_, int y_) : x(x_), y(y_) {}
int x;
int y;
};
struct Bar {
Bar(Foo first_, Foo second_) : first(first_), second(second_) {}
Foo first;
Foo second;
};
#include <iostream>
int main() {
Bar b = { { 1, 2 }, { 3, 4 } };
std::cout << b.first.x << ", " << b.first.y << ", ";
std::cout << b.second.x << ", " << b.second.y << std::endl;
// ^ Output: 1, 2, 3, 4
}