gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:30:46 24 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/5563000/

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