C++隐式转换序列中的三种转换
Three conversions in C++ implicit conversion sequence
http://en.cppreference.com/w/cpp/language/implicit_cast 的页面指出在隐式转换序列中最多可以完成三个转换序列:
Implicit conversion sequence consists of the following, in this order:
- zero or one standard conversion sequence
- zero or one user-defined conversion
- zero or one standard conversion sequence
这三种情况的例子是什么?
我不明白这三个问题怎么会同时发生。这意味着您可以在两种语言定义的类型(比如 int*
和 char
)之间使用用户定义的 class(称之为 Stuff
).在我看来,没有理由要 int*
>Stuff
>char
(例如)。
换句话说,从A
到B
的隐式转换意味着“A
可以理解为B
”。为语言定义的类型加上这样一条规则听起来很奇怪,更奇怪的是用“A
可以理解为我的classC
”和"my class C
can be understood as being B
"来解释。
但是要使规则有意义,提供 1. 和 2. 的示例以及 2. 和 3. 的示例就足够了。这很容易做到。
如果您还没有弄清楚,只需考虑一个 class(比方说 Date
),它可以转换为一个 int
(用户定义的 Date::int()
) 并且可以从 int
(复制构造函数)创建。然后,通过考虑 int
>long
和 short
到 int
的转换,你有你的例子。
Date d;
short a = 1234;
d = a; // Convertion short>int and int>Date (1. and 2.)
long b = d; // Convertion Date>int and int>long (2. and 3.)
http://en.cppreference.com/w/cpp/language/implicit_cast 的页面指出在隐式转换序列中最多可以完成三个转换序列:
Implicit conversion sequence consists of the following, in this order:
- zero or one standard conversion sequence
- zero or one user-defined conversion
- zero or one standard conversion sequence
这三种情况的例子是什么?
我不明白这三个问题怎么会同时发生。这意味着您可以在两种语言定义的类型(比如 int*
和 char
)之间使用用户定义的 class(称之为 Stuff
).在我看来,没有理由要 int*
>Stuff
>char
(例如)。
换句话说,从A
到B
的隐式转换意味着“A
可以理解为B
”。为语言定义的类型加上这样一条规则听起来很奇怪,更奇怪的是用“A
可以理解为我的classC
”和"my class C
can be understood as being B
"来解释。
但是要使规则有意义,提供 1. 和 2. 的示例以及 2. 和 3. 的示例就足够了。这很容易做到。
如果您还没有弄清楚,只需考虑一个 class(比方说 Date
),它可以转换为一个 int
(用户定义的 Date::int()
) 并且可以从 int
(复制构造函数)创建。然后,通过考虑 int
>long
和 short
到 int
的转换,你有你的例子。
Date d;
short a = 1234;
d = a; // Convertion short>int and int>Date (1. and 2.)
long b = d; // Convertion Date>int and int>long (2. and 3.)