C++ 逻辑非(!) 运算符重载
逻辑非(!) 运算符是一元运算符,出现在它们所操作对象的左边 !obj
逻辑非(!) 运算符运算符返回的类型为 bool
类型
- 当对象为真值时,逻辑非(!) 运算符返回假
- 当对象为假值时,逻辑非(!) 运算符返回真
/** * file: main.cpp * author: 简单教程(www.twle.cn) * * Copyright © 2015-2065 www.twle.cn. All rights reserved. */ #include <iostream> class Rect { private: int width; int height; public: Rect(){ width = 0; height = 0; } Rect( int a, int b ) { width = a; height = b; } int area () { return width * height; } // 当 width 或者 height 有一个小于 0 则返回 true bool operator!() { if ( width <= 0 || height <= 0 ) { return true; } return false; } }; int main() { Rect r1, r2(-1,1), r3(-1,-1), r4(1,1); if (!r1) std::cout << "r1 is not a rectangle\n"; else std::cout << "r1 is a rectangle\n"; if (!r2) std::cout << "r2 is not a rectangle\n"; else std::cout << "r2 is a rectangle\n"; if (!r3) std::cout << "r3 is not a rectangle\n"; else std::cout << "r3 is a rectangle\n"; if (!r4) std::cout << "r4 is not a rectangle\n"; else std::cout << "r4 is a rectangle\n"; return 0; }
使用 g++ main.cpp && ./a.out
命令编译和运行以上范例,输出结果如下:
r1 is not a rectangle r2 is not a rectangle r3 is not a rectangle r4 is a rectangle