gpt4 book ai didi

c++ - C++ 运算符中的隐式类型转换规则

转载 作者:行者123 更新时间:2023-11-30 17:32:16 25 4
gpt4 key购买 nike

我想更好地知道何时应该施放。 C++中加法、乘法等时的隐式类型转换规则是什么?例如

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

诸如此类...

表达式是否总是被计算为更精确的类型? Java 的规则是否有所不同?如果我对这个问题的措辞不准确,请纠正我。

最佳答案

在 C++ 中,运算符(对于 POD 类型)始终作用于相同类型的对象。
因此,如果它们不相同,则会将其提升为与另一个匹配。
运算结果的类型与操作数相同(转换后)。

if:
either is long double other is promoted > long double
either is double other is promoted > double
either is float other is promoted > float
either is long long unsigned int other is promoted > long long unsigned int
either is long long int other is promoted > long long int
either is long unsigned int other is promoted > long unsigned int
either is long int other is promoted > long int
either is unsigned int other is promoted > unsigned int
either is int other is promoted > int

Otherwise:
both operands are promoted to int

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

在所有表达式中,int 在执行操作之前都会提升为 float。运算结果是一个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++ - C++ 运算符中的隐式类型转换规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24283950/

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