C++,隐式转换/构造函数是如何确定的?
C++ 如何确定几层深度的对象的隐式转换/构造? 例如:
struct A {};
struct B: A {};
struct C { operator B() { return B(); } };
void f(A a) {}
int main(void)
{
f(C());
}
它是否创建所有可能转换的树并选择适当的终端?还有别的事吗?谢谢
How does C++ determine implicit conversion/construction of objects few levels deep?
for example:
struct A {};
struct B: A {};
struct C { operator B() { return B(); } };
void f(A a) {}
int main(void)
{
f(C());
}
Does it create tree of all possible conversions and chooses appropriate terminal? Something else? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对
f()
的调用需要两次转换,一次用户定义的转换(C
到B
)和一次内置转换(派生-to-base:B
到A
)。当需要零个或一个用户定义的转换时,具有不匹配参数的调用会成功。如果不同的转换(内置或用户定义的)会成功,那么,如果所有可能的方式在所需的转换数量/种类上都相同,则调用是不明确的,并且编译器需要发出诊断。标准没有指定编译器如何实现这一点。
The call to
f()
would need two conversions, one user-defined conversion (C
toB
) and one built-in conversion (derived-to-base:B
toA
). Calls with non-matching arguments succeed when they would need zero or one user-defined conversions. If different conversions (built-in or user-defined) would succeed, then, if all possible ways are equal in the number/kind of conversions they need, the call is ambiguous and the compiler needs to emit a diagnostic.How compilers implement this isn't specified by the standard.
标准没有对此进行规定。它仅指定结果。每个不同的编译器供应商都可以以他们选择的任何方式实现这一点,只要他们给出正确的结果。
所以可能有很多不同的方法
The standard doesn't specify this. It only specifies the outcome. Each different compiler vendor can implement this any way they choose, as long as they give the correct result.
So there's probably a whole bunch of different approaches out there