多重隐式构造函数转换 [英] Multiple implicit constructor conversion

查看:147
本文介绍了多重隐式构造函数转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

隐式构造函数转换似乎只适用于单次转换。

Implicit constructor conversion only seems to work with a single conversion.

class A {
public:
    A(std::string s) {}
};
class B {
public:
    B(A a) { }
};

使用上述代码,运行

B b{std::string("Hey")};

可以正常工作。

另一方面,

B b{"Hey"};

不会。

真的只有一个单一的转换,为什么是这种情况?为了避免在提供不同构造函数时的可能模糊性?

Does constructor conversion really only work with a single conversion, and why is this the case? To avoid possible ambiguity when different constructors are provided?

推荐答案


构造函数转换是否只对单个转换有效?

Does constructor conversion really only work with a single conversion?

单个用户定义的转换,是的。


为什么会出现这种情况?

why is this the case?

简单的答案是因为这是指定的语言。

The simple answer is because that's how the language is specified.

更有用的是:编译器将必须考虑它知道的每种类型,以确定是否存在合适的中间类型。不仅这将是很多工作(组合爆炸,如果你允许任意数量的转换),但你可能会得到模糊,微妙的行为变化取决于哪种类型恰好在那一点定义代码。

More usefully: if two conversions were allowed, then the compiler would have to consider every type that it knows about, to determine whether there's a suitable intermediate type. Not only would this be a lot of work (with a combinatorial explosion, if you allow any number of conversions), but you're likely to get ambiguities, and subtle changes of behaviour depending on which types happen to be defined at that point in the code.

这篇关于多重隐式构造函数转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆