开发者

Why is this operator called in C++?

I dont understand, why is the aaa operator called in the 2nd 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 mai开发者_如何学Cn()
{
    MyClass a;
    MyClass b;

    if(a && b) {}
}


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

Because the class doesn't have an operator that turns MyClass to a boolean, it searches for the best cast.

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

Overloading typecasts

Conversion Functions (C++)


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


It looks like a type cast operator. Oops, never mind, misread 'why is this operator called' for 'what is this operator called'


Ok, I tested your code and examined it some more. So operator aaa is a type cast to type aaa. Type aaa is a pointer to a member function of type void func(). ThisTypeDoesNotSupportComparisons is a function of type aaa. operator aaa gets called and returns the pointer to function.

I think it is called because the if allows to use pointers to functions as well. You can test if a pointer is NULL or not, and this is the closest the compiler can find, so if calls the operator aaa and tests if the pointer returned is zero.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜