What exactly is the ->* operator?

后端 未结 4 1664
执笔经年
执笔经年 2021-01-14 06:32

I\'ve never used it before and just stumbled upon it in an article... I thought it would be the equivalent to *x->y but apparently it isn\'t.

Here\'s

相关标签:
4条回答
  • 2021-01-14 06:34

    Its used when you have pointers to member functions.

    When you have a pointer to a function of a class, you call it in much the same way you would call any member function

    object.membername( ... )

    or

    objectptr->membername( ... )

    but when you have a member function pointer, an extra * is needed after the . or -> in order that the compiler understand that what comes next is a variable, not the actual name of the function to call.

    Here's an example of how its used.

    class Duck
    {
    public:
    
      void quack() { cout << "quack" << endl; }
      void waddle() { cout << "waddle" << endl; }
    };
    
    typedef void (Duck::*ActionPointer)();
    
    ActionPointer myaction = &Duck::quack;
    
    void takeDuckAction()
    {    
        Duck myduck;
        Duck *myduckptr = &myduck;
    
        (myduck.*myaction)();
        (myduckptr->*myaction)();
    }
    
    0 讨论(0)
  • 2021-01-14 06:41

    Pointer-to-Member Operators: .* and ->*

    0 讨论(0)
  • 2021-01-14 06:49

    It defines a pointer to a member.

    In an expression containing the –>* operator, the first operand must be of the type "pointer to the class type" of the type specified in the second operand, or it must be of a type unambiguously derived from that class. MSDN

    0 讨论(0)
  • 2021-01-14 06:55

    The .* and ->* operators will point to member functions of a class or structure. The code below will show a simple example of how to use the .* operator, if you change the line: Value funcPtr = &Foo::One; to Value funcPtr = &Foo::Two; the result displayed will change to 1000 since that function is inValue*2

    for example Taken From Here:

    #include <iostream>
    #include <stdlib.h>
    
    class Foo { 
      public: 
        double One( long inVal ) { return inVal*1; }
        double Two( long inVal ) { return inVal*2; }
    }; 
    
    typedef double (Foo::*Value)(long inVal); 
    
    int main( int argc, char **argv ) { 
      Value funcPtr = &Foo::One; 
    
      Foo foo;
    
      double result = (foo.*funcPtr)(500); 
      std::cout << result << std::endl;
      system("pause");
      return 0; 
    } 
    
    0 讨论(0)
提交回复
热议问题