gpt4 book ai didi

c++ - boolean 复合赋值中的隐式转换?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:16:42 24 4
gpt4 key购买 nike

我想了解在以下情况下会发生什么:

bool b = false;
float f = 3.14;
char c = 1;
int i = 2;
unsigned int u = 3;
long long int ll = 4;
unsigned long long int ull = 5;

b += f;
b += c;
b += i;
b += u;
b += ll;
b += ull;

b &= f;
b &= c;
b &= i;
b &= u;
b &= ll;
b &= ull;

b <<= f;
b <<= c;
b <<= i;
b <<= u;
b <<= ll;
b <<= ull;

或者说,按照标准做了哪些隐式转换?

其他问题:如果为假设的 bool 类提供的复合赋值签名的唯一形式是以下形式,结果是否相同:

class bool {bool& operator op=(int x) noexcept;}; // op <=> +,-,&,|...

最佳答案

所有这些情况下的相关转换都是 boolean 转换,[conv.bool]:

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

有两个异常(exception):

b &= f;
b <<= f;

前者,因为[expr.bit.and]:

The usual arithmetic conversions are performed; the result is the bitwise AND function of the operands. The operator applies only to integral or unscoped enumeration operands.

而后者,因为 [expr.shift]:

The operands shall be of integral or unscoped enumeration type and integral promotions are performed.

因为 float 既不是整数也不是无作用域的枚举类型,所以这两个操作是无效的。


对于您的(我在这里重命名您的类(class)):

class Bool {Bool& operator op=(int x) noexcept;}; // op <=> +,-,&,|...

我们会陷入三种转换中的一种,具体取决于类型。对于 charbool,我们进行积分提升,[conv.prom]:

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned
int
.
[...]
A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

对于其他整数类型,积分转换,来自[conv.integral]:

A prvalue of an integer type can be converted to a prvalue of another integer type. A prvalue of an unscoped enumeration type can be converted to a prvalue of an integer type.
[...]
If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.

对于 float,一个浮点积分转换,来自 [conv.fpint]:

A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.

关于c++ - boolean 复合赋值中的隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32684369/

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