我可以在C ++中对int值使用not运算符吗? [英] Can I use the not operator in C++ on int values?
问题描述
奇怪的问题,但是有人向我展示了这一点, 我想知道你能不能用! C ++中的int运算符? (对我来说很奇怪).
Strange question, but someone showed me this, I was wondering can you use the not ! operator for int in C++? (its strange to me).
#include <iostream>
using namespace std;
int main()
{
int a=5, b=4, c=4, d;
d = !( a > b && b <= c) || a > c && !b;
cout << d;
system ("pause");
return 0;
}
推荐答案
是.对于整数类型,如果操作数为零,则!
返回true
,否则返回false
.
Yes. For integral types, !
returns true
if the operand is zero, and false
otherwise.
所以!b
在这里仅表示b == 0
.
在将值转换为bool
的特殊情况下. !b
可以看作是!((bool)b)
,所以问题是b
的真实性"是什么.在C ++中,算术类型,指针类型和枚举可以转换为bool
.当值为0或为null时,结果为false
,否则为true
(C ++§4.1.2).
This is a particular case where a value is converted to a bool
. The !b
can be viewed as !((bool)b)
so the question is what is the "truthness" of b
. In C++, arithmetic types, pointer types and enum can be converted to bool
. When the value is 0 or null, the result is false
, otherwise it is true
(C++ §4.1.2).
当然,自定义类甚至可以重载operator!
或operator
< 类型可以转换为bool >以允许其类使用!b
.例如,std::stream
重载了operator!
和operator void*
来检查故障位,因此像这样的习惯用法
Of course custom classes can even overload the operator!
or operator
<types can be convert to bool> to allow the !b
for their classes. For instance, std::stream
has overloaded the operator!
and operator void*
for checking the failbit, so that idioms like
while (std::cin >> x) { // <-- conversion to bool needed here
...
可以使用.
(但是您的代码!( a > b && b <= c) || a > c && !b
只是一个秘密.)
(But your code !( a > b && b <= c) || a > c && !b
is just cryptic.)
这篇关于我可以在C ++中对int值使用not运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!