在 C++ 中,您可以使用 bool 和 int 运算符执行哪些操作?

What operations can you perform with bool and int operators in C++?

我有一个变量,可以从0到1不同,所以我想使用bool 类型 用于保存此值。

C++中基于这个想法我可以做什么操作,第一个操作数的类型是bool 第二个 int 或 float?

例如,这个有效吗?

bool exists;
int value;
(...)
value += exists;
value *= exists;

如果是,直到 c++ 将这些值转换为它们的 二进制适当值 并且发现执行 操作没有问题 在那些 二进制数 上,用 不同的操作数 进行运算是 有效的

it is valid to do the operations with operands that differ?

value += exists;
value *= exists;

是的,它是有效的,bool 类型隐式转换为 int。它类似于您对带有混合 intshort 操作数的运算符( + 、 - )所做的操作。

是的,这些操作存在,它们可以在 C++ 标准第 13.6 节中找到(注意,bool 是一个整数类型,这也使其成为算术类型):

For every triple (L, VQ, R), where L is an arithmetic type, VQ is either volatile or empty, and R is a promoted arithmetic type, there exist candidate operator functions of the form

VQ L & operator=(VQ L &, R );
VQ L & operator*=(VQ L &, R );
VQ L & operator/=(VQ L &, R );
VQ L & operator+=(VQ L &, R );
VQ L & operator-=(VQ L &, R );

语义在第 5.18 节中定义:

The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. In += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type. In all other cases, E1 shall have arithmetic type.

If the left operand is not of class type, the expression is implicitly converted (Clause 4) to the cv-unqualified type of the left operand.