#include <iostream>
struct Gadget
{
Gadget() { puts("Gadget default"); }
Gadget(char const *a) { puts("Gadget-const char* constructor"); }
Gadget(Gadget const &other) { puts("Gadget copy"); }
~Gadget() { puts("\nGadget destruction"); }
};
struct Work
{
Work() { puts("default"); }
Work(const Gadget &a) { puts("Work-Gadget constructor"); }
// Work(char const *a) { puts("Work-const char* constructor"); }
Work(Work const &other) { puts("copy"); }
~Work() { puts("\nWork destruction"); }
};
int main()
{
using namespace std;
Work w = "std"; // error here;
}
但Work w("std"); // works fine
Work w = Gadget("std"); // works fine
Work w = Work("std"); // works fine
c++ 可以做的隐式转换有什么限制吗?如果是这样,那么隐式转换发生在什么上下文中?
最佳答案
只有一个 user-defined conversion允许在 implicit conversion sequence . (顺便说一句,标准转换没有这样的限制。)Work w = "std";
执行 copy initialization ,它需要两个用户定义的转换,一个来自 char const *
至 Gadget
,还有一个来自 Gadget
至 Work
.Work w("std");
执行 direct initialization ,只需要一个用户定义的转换(从 char const *
到 Gadget
),那么转换后的 Gadget
传递给 Work
的构造函数直接构建w
.
the implicit conversion in copy-initialization must produce
T
directly from the initializer, while, e.g. direct-initialization expects an implicit conversion from the initializer to an argument ofT
's constructor.
在
Work w = Work("std");
,临时Work
明确构造为 Work("std")
(其工作原理如上所述),然后 w
从临时 Work
复制初始化.在
Work w = Gadget("std");
,临时Gadget
明确构造为 Gadget("std")
,然后 w
从临时 Gadget
复制初始化;其中只需要一个用户定义的转换(从 Gadget
到 Work
)。
关于c++ - 在初始化类类型时,C++ 可以进行多少次隐式转换来将一种用户定义类型转换为另一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64999087/