Why is this statement called in C ++?

I do not understand why the aaa operator is called in the second last line?

#include <iostream> class MyClass { private: typedef void (MyClass::*aaa)() const; void ThisTypeDoesNotSupportComparisons() const {} public: operator aaa() const { return (true) ? &MyClass::ThisTypeDoesNotSupportComparisons : 0; } }; int main() { MyClass a; MyClass b; if(a && b) {} } 
+4
source share
3 answers

The compiler is looking for the best match for (a & b) .

Since the class does not have an operator that turns MyClass into a boolean, it searches for the best result.

Operator

aaa () const is a cast to a pointer of type aaa. Pointers can be evaluated in an if clause.

Type drive overload

Conversion Functions (C ++)

+6
source

Your variables are used in the expression. The type itself does not have an && operator defined for it, but converted to a type (pointer) that can be used in the expression. Thus, the conversion operator is called.

+3
source

It looks like a cast type operator. Oh, never mind, read "why this operator is called" for, "what this operator is called"


Ok, I checked your code and inspected it a bit more. Thus, the operator aaa is a cast type of type aaa. Type aaa is a pointer to a member function of type void func (). ThisTypeDoesNotSupportComparisons is aaa type function. the aaa operator is called and returns a function pointer.

I think it is called because if allows the use of function pointers. You can check if the pointer is NULL or not, and the closest compiler can find it, therefore, if it calls the aaa operator and checks if the pointer is returned.

0
source

Source: https://habr.com/ru/post/1345399/


All Articles