C ++隐式转换序列中的三个转换 [英] Three conversions in C++ implicit conversion sequence

查看:123
本文介绍了C ++隐式转换序列中的三个转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://en.cppreference.com/w/cpp/language的网页/ implicit_cast 声明可以在隐式转换序列中完成多达三个转换序列:


隐式转换序列由


  1. 零或一个标准转换序列



解决方案

我没有看到这三种情况如何在一行中发生。这意味着你可以在两个语言定义类型之间进行隐式转换(比如说 int * char )一个用户定义类的中间(调用 Stuff )。在我看来,没有理由你会想做 int * > Stuff > char (例如)。



换句话说,从 A B的隐式转换表示 A 可以理解为 B 。添加这样的语言定义类型的规则听起来很奇怪,甚至可以通过 A 来解释它,可以理解为我的类 C 和我的类 C 可以理解为 B




但是为了使规则有意义,足以提供示例1和2,以及示例2。这很容易做。



如果你没有想出来,只要考虑一个类(让我们说 Date )可以转换为 int (用户定义 Date :: int()可以从 int (复制构造函数)创建。然后,考虑转换 int > long short int 你有你的例子。

  
short a = 1234;
d = a; //转换short> int和int>日期(1.和2.)
long b = d; //转换日期> int和int> long(2.和3.)


The page at http://en.cppreference.com/w/cpp/language/implicit_cast states that up to three conversion sequences can be done in an implicit conversion sequence:

Implicit conversion sequence consists of the following, in this order:

  1. zero or one standard conversion sequence
  2. zero or one user-defined conversion
  3. zero or one standard conversion sequence

What is an example of all three occurring?

解决方案

I don't see how all three could occur in a row. This would mean that you enable an implicit conversion between two language-defined types (let's say int* and char) with the intermediate of an user-defined class (call it Stuff). In my opinion, there is no reason for which you would want to do int*>Stuff>char (for example).

In other words, an implicit conversion from A to B means "A can be understood as being B". It sounds weird to add such a rule for language-defined type, and even weirder to explain it by "A can be understood as my class C" and "my class C can be understood as being B".


But for the rule to make sense, it is enough to provide an example of 1. and 2., and an example of 2. and 3. This is easy to do.

If you haven't figured it out, just consider a class (let's say Date) that can be converted to an int (user defined Date::int()) and that can be created from an int (copy constructor). Then, by considering the conversion int>long and short to int you have your examples.

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.)

这篇关于C ++隐式转换序列中的三个转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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