不允许对自定义类型进行多次隐式转换? [英] Multiple implicit conversions on custom types not allowed?
问题描述
class C {
public:
C() { }
};
class B {
public:
B(C c) { }
B() { }
};
class A {
public:
A(bool b) { }
A(B b) { }
};
int main() {
A a1 = true; // bool -> A is allowed
A a2 = B(); // B -> A is allowed
A a3 = 7; // int -> bool -> A is allowed
A a4 = C(); // C -> B -> A isn't allowed
}
为什么我可以使用两步隐式转换 bool
但不能与 C
一起使用?
描述多步隐式转换的一般规则是什么?
Why I can use two-step implicit conversion with bool
but can't use it with C
?
What is the general rule describing multistep implicit conversion?
推荐答案
int -> bool -> A
是允许的,因为 int-> bool
转换不是用户定义的。
is allowed because the int->bool
conversion isn't user-defined.
1类对象的类型转换可以通过构造函数
和转换函数指定。这些转换称为用户定义的
转换,用于隐式类型转换(第4节),
初始化(8.5)和显式类型转换(5.4,5.2.9)。
1 Type conversions of class objects can be specified by constructors and by conversion functions. These conversions are called user-defined conversions and are used for implicit type conversions (clause 4), for initialization (8.5), and for explicit type conversions (5.4, 5.2.9).
2用户定义的转换仅在它们是无歧义的
(10.2,12.3.2)时应用。转换服从访问控制规则(第11节)。
访问控制在模糊解析(3.4)之后应用。
2 User-defined conversions are applied only where they are unambiguous (10.2, 12.3.2). Conversions obey the access control rules (clause 11). Access control is applied after ambiguity resolution (3.4).
3 [注:
有关在函数调用
中使用转换的讨论以及下面的示例,请参见13.3。 -end note]
3 [ Note: See 13.3 for a discussion of the use of conversions in function calls as well as examples below. —end note ]
4最多一个用户定义的
转换(构造函数或转换函数)将
隐式应用于单个
这篇关于不允许对自定义类型进行多次隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!