What is ->* operator in C++?

前端 未结 3 1336
执念已碎
执念已碎 2020-12-30 00:16

C++ continues to surprise me. Today i found out about the ->* operator. It is overloadable but i have no idea how to invoke it. I manage to overload it in my class but i hav

相关标签:
3条回答
  • 2020-12-30 00:48

    Just like .*, ->* is used with pointers to members. There's an entire section on C++ FAQ LITE dedicated to pointers-to-members.

    #include <iostream>
    
    struct foo {
        void bar(void) { std::cout << "foo::bar" << std::endl; }
        void baz(void) { std::cout << "foo::baz" << std::endl; }
    };
    
    int main(void) {
        foo *obj = new foo;
        void (foo::*ptr)(void);
    
        ptr = &foo::bar;
        (obj->*ptr)();
        ptr = &foo::baz;
        (obj->*ptr)();
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-30 01:00

    Like any other opperator, you can also call it explicitly:

    a.operator->*(2);
    
    0 讨论(0)
  • 2020-12-30 01:04

    The overloaded ->* operator is a binary operator (while .* is not overloadable). It is interpreted as an ordinary binary operator, so in you original case in order to call that operator you have to do something like

    A a;
    B* p = a->*2; // calls A::operator->*(int)
    

    What you read in the Piotr's answer applies to the built-in operators, not to your overloaded one. What you call in your added example is also the built-in operator, not your overloaded one. In order to call the overloaded operator you have to do what I do in my example above.

    0 讨论(0)
提交回复
热议问题