C ++运算符中的隐式类型转换规则 [英] Implicit type conversion rules in C++ operators

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

问题描述

我想要更好地知道我什么时候应该投降。例如,

I want to be better about knowing when I should cast. What are the implicit type conversion rules in C++ when adding, multiplying, etc. For example,

int + float = ?
int * float = ?
float * int = ?
int / float = ?
float / int = ?
int / int = ?
int ^ float = ?

et cetera ...

et cetera...

表达式总是被评估为更精确的类型? Java的规则有所不同吗?

Will the expression always be evaluated as the more precise type? Do the rules differ for Java? Please correct me if I have worded this question inaccurately.

推荐答案

在C ++操作符对同一类型的对象。

因此,如果它们不相同,那么将被提升为匹配另一个。

操作结果的类型与操作数相同(转换后)。

In C++ operators (for POD types) always act on objects of the same type.
Thus if they are not the same one will be promoted to match the other.
The type of the result of the operation is the same as operands (after conversion).

If either is      long          double the other is promoted to      long          double
If either is                    double the other is promoted to                    double
If either is                    float  the other is promoted to                    float
If either is long long unsigned int    the other is promoted to long long unsigned int
If either is long long          int    the other is promoted to long long          int
If either is long      unsigned int    the other is promoted to long      unsigned int
If either is long               int    the other is promoted to long               int
If either is           unsigned int    the other is promoted to           unsigned int
If either is                    int    the other is promoted to                    int
Both operands are promoted to int

注意。操作的最小大小为 int 。因此,在操作之前, short / char 被提升为 int

Note. The minimum size of operations is int. So short/char are promoted to int before the operation is done.

在所有的表达式中, int 被提升为 code>,然后再执行操作。该操作的结果是 float

In all your expressions the int is promoted to a float before the operation is performed. The result of the operation is a float.

int + float =>  float + float = float
int * float =>  float * float = float
float * int =>  float * float = float
int / float =>  float / float = float
float / int =>  float / float = float
int / int                     = int
int ^ float =>  <compiler error>

这篇关于C ++运算符中的隐式类型转换规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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