我可以在C ++中对int值使用not运算符吗? [英] Can I use the not operator in C++ on int values?

查看:89
本文介绍了我可以在C ++中对int值使用not运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

奇怪的问题,但是有人向我展示了这一点, 我想知道你能不能用! 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆