0

We can overload + operator. But how is it possible in case of ! Operator? It just converts logical 1 to 0 or vice versa.

#include <iostream> using namespace std; class MyClass { public: int var; MyClass() { } MyClass(int a) : var(a) { } MyClass operator+(MyClass &obj) { MyClass res; res.var= this->var+obj.var; return res; } }; int main() { MyClass obj1(12), obj2(55); MyClass res = obj1+obj2; cout << res.var; }

4th Aug 2017, 8:19 PM
Bhavesh Mahale
Bhavesh Mahale - avatar
4 Respostas
0
That is up to you to define, for all we know you might want to add 666 to it or whatever you want to do with it like so: #include <iostream> class MyClass { public: MyClass(int x):var(x){} MyClass operator+(MyClass& other) { return {var + other.var}; } MyClass operator!() { return {var + 666}; } operator int() { return var; } private: int var; }; int main() { MyClass x(5); std::cout << !x << " " << !!x << std::endl; }
4th Aug 2017, 9:07 PM
Dennis
Dennis - avatar
0
thanks
5th Aug 2017, 11:42 AM
Bhavesh Mahale
Bhavesh Mahale - avatar
0
but I am not getting why we write " !x "?What really this concept is?
5th Aug 2017, 11:43 AM
Bhavesh Mahale
Bhavesh Mahale - avatar
0
It's the boolean negation operator. It converts true to false and false to true. !0(false) becomes 1(true) !1(true) becomes 0(false) !7(true) becomes 0(false) etc... It is often used as a toggle as in: bool lights_enabled = false; lights_enabled = !lights_enabled; //Lights are now on lights_enabled = !lights_enabled; //Lights are off again or to negate a boolean return value like !isValid(). Another trick I sometimes see is double !! which converts any non zero integer to 1 and keeps 0 at 0.
5th Aug 2017, 2:02 PM
Dennis
Dennis - avatar