gpt4 book ai didi

c++ - 在初始化类类型时,C++ 可以进行多少次隐式转换来将一种用户定义类型转换为另一种类型?

转载 作者:行者123 更新时间:2023-12-03 23:02:05 26 4
gpt4 key购买 nike

#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 ,还有一个来自 GadgetWork .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 of T's constructor.


Work w = Work("std"); ,临时 Work明确构造为 Work("std") (其工作原理如上所述),然后 w从临时 Work 复制初始化.
Work w = Gadget("std"); ,临时 Gadget明确构造为 Gadget("std") ,然后 w从临时 Gadget 复制初始化;其中只需要一个用户定义的转换(从 GadgetWork )。

关于c++ - 在初始化类类型时,C++ 可以进行多少次隐式转换来将一种用户定义类型转换为另一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64999087/

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