我可以在 C++ 中使用 not 运算符吗?关于 int 值?
奇怪的问题,但有人向我展示了这个, 我想知道你能用 not 吗? C++ 中 int 的运算符? (这对我来说很奇怪)。
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的。对于整型,如果操作数为零,
!
返回true
,否则返回false
。所以这里的
!b
仅仅意味着b == 0
。这是一种将值转换为
bool
的特殊情况。!b
可以被视为!((bool)b)
所以问题是b
的“真实性”是什么。在 C++ 中,算术类型、指针类型和枚举都可以转换为bool
。当值为 0 或 null 时,结果为false
,否则为true
(C++ §4.1.2)。当然,自定义类甚至可以重载
operator!
或operator
<类型可以转换为 bool>允许其类使用!b
。例如,std::stream
已经重载了operator!
和operator void*
来检查失败位,因此可以使用类似的习惯用法。
(但是你的代码
!( a > b && b <= c) || a > c && !b
只是神秘的。)Yes. For integral types,
!
returnstrue
if the operand is zero, andfalse
otherwise.So
!b
here just meansb == 0
.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" ofb
. In C++, arithmetic types, pointer types and enum can be converted tobool
. When the value is 0 or null, the result isfalse
, otherwise it istrue
(C++ §4.1.2).Of course custom classes can even overload the
operator!
oroperator
<types can be convert to bool> to allow the!b
for their classes. For instance,std::stream
has overloaded theoperator!
andoperator void*
for checking the failbit, so that idioms likecan be used.
(But your code
!( a > b && b <= c) || a > c && !b
is just cryptic.)最初,C(C++ 的基础)中没有布尔类型。相反,值“true”被分配给任何非零值,而值“false”被分配给任何计算为零的值。这种行为在 C++ 中仍然存在。因此,对于
int x
来说,表达式!x
表示“x
not true”,即“x
not非零”,即如果x
为零则为真。Originally, in C (on which C++ is based) there was no Boolean type. Instead, the value "true" was assigned to any non-zero value and the value "false" was assigned to anything which evaluates to zero. This behavior still exists in C++. So for an
int x
, the expressions!x
means "x
not true", which is "x
not non-zero", i.e. it's true ifx
is zero.可以,
!b
相当于(b == 0)
。You can,
!b
is equivalent to(b == 0)
.int 的测试对于非零值是 true,对于零值是 false,因此 not 仅对于零值是 true,对于非零值是 false。
The test for int is true for non-zero values and false for zero values, so not is just true for zero values and false for non-zero values.
内置
!
运算符将其参数转换为bool
。该标准指定存在任何算术类型的转换(int
、char
、....float
、double
...) 到 bool。如果源值为 0,则结果为true
,否则为false
The build-in
!
operator converts its argument tobool
. The standard specifies that there exists a conversion from any arithmetic type(int
,char
,....float
,double
...) to bool. If the source value is 0 the result istrue
, otherwise it isfalse