Reputation: 3
I need to overload this operator (mainMenu is class type called 'Menu'):
if (mainMenu) {
cout << "The mainMenu is valid and usable." << endl;
}
I tried this, but it didn't work:
bool operator!(const Menu& lobj);
Upvotes: 0
Views: 53
Reputation: 311126
In the condition of this if statement
if (mainMenu)
the logical negation operator !
is not used.
Instead you could write for example
if ( !!mainMenu )
However it is better to declare an explicit conversion operator like
explicit operator bool() const;
In this case you could write
if (mainMenu)
Here is a demonstrative program that shows a difference between these operators.
#include <iostream>
struct A
{
bool operator !() const
{
return false;
}
explicit operator bool() const
{
return true;
}
};
int main()
{
if ( !!A() ) std::cout << "Hello\n";
if ( A() ) std::cout << "World!\n";
return 0;
}
The program output is
Hello
World!
Upvotes: 7