gpt4 book ai didi

c++ - 不允许对自定义类型进行多次隐式转换?

转载 作者:IT老高 更新时间:2023-10-28 23:17:30 25 4
gpt4 key购买 nike

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 使用它?描述多步隐式转换的一般规则是什么?

最佳答案

没有多步用户自定义隐式转换。

int -> bool -> A

是允许的,因为 int->bool 转换不是用户定义的。

12.3 转换 [class.conv]

1 Type conversions of class objects can be specified by constructorsand by conversion functions. These conversions are called user-definedconversions and are used for implicit type conversions (clause 4), forinitialization (8.5), and for explicit type conversions (5.4, 5.2.9).

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 [ Note:See 13.3 for a discussion of the use of conversions in function callsas well as examples below. —end note ]

4 At most one user-definedconversion (constructor or conversion function) is implicitly appliedto a single value.

关于c++ - 不允许对自定义类型进行多次隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12847272/

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