Calling C++ class methods via a function pointer

前端 未结 10 970
醉酒成梦
醉酒成梦 2020-11-22 06:47

How do I obtain a function pointer for a class member function, and later call that member function with a specific object? I’d like to write:

class Dog : A         


        
10条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 07:09

    Minimal runnable example

    main.cpp

    #include 
    
    class C {
        public:
            int i;
            C(int i) : i(i) {}
            int m(int j) { return this->i + j; }
    };
    
    int main() {
        // Get a method pointer.
        int (C::*p)(int) = &C::m;
    
        // Create a test object.
        C c(1);
        C *cp = &c;
    
        // Operator .*
        assert((c.*p)(2) == 3);
    
        // Operator ->*
        assert((cp->*p)(2) == 3);
    }
    

    Compile and run:

    g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
    ./main.out
    

    Tested in Ubuntu 18.04.

    You cannot change the order of the parenthesis or omit them. The following do not work:

    c.*p(2)
    c.*(p)(2)
    

    GCC 9.2 would fail with:

    main.cpp: In function ‘int main()’:
    main.cpp:19:18: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘p (...)’, e.g. ‘(... ->* p) (...)’
       19 |     assert(c.*p(2) == 3);
          |
    

    C++11 standard

    .* and ->* are a single operators introduced in C++ for this purpose, and not present in C.

    C++11 N3337 standard draft:

    • 2.13 "Operators and punctuators" has a list of all operators, which contains .* and ->*.
    • 5.5 "Pointer-to-member operators" explains what they do

提交回复
热议问题