C++: Calling member function via pointer

前端 未结 1 1917
暗喜
暗喜 2020-12-03 10:50

I have this example code of using pointer to member function, which I want to change during runtime, but I cannot make it work. I\'ve already tried this->*_currentP

相关标签:
1条回答
  • 2020-12-03 11:29

    You need to tell the compiler which class the foos are coming from (otherwise it thinks they're functions from global scope):

    void A::setPtr(int v){
        if(v == 1){
            _currentPtr = &A::foo1;
                      //  ^^^^
        } else {
            _currentPtr = &A::foo2;
                      //  ^^^^
        }
    }
    

    and you need a set of parentheses here:

    std::cout << (this->*_currentPtr)(4,5);
              // ^                  ^
    
    0 讨论(0)
提交回复
热议问题