not operator in C++ for int

我看数据结构的时候,看到这样的代码:

 

Rank size()const { return _size;}

bool empty() const { return !_size;}

 

我对 return !_size; 这句感到不解,后来在 stackoverflow 找到了一个类似的问题:

http://stackoverflow.com/questions/4123550/not-operator-in-c-for-int

 

Yes. For integral types, ! returns true if the operand is zero, and false otherwise.

So !b here just means b == 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" 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).

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
  ...

can be used.

posted @ 2016-01-21 11:02  迟立文  阅读(166)  评论(0编辑  收藏  举报