从继承的函数指针调用base方法

时间:2016-08-26 23:31:30

标签: c++ inheritance function-pointers

我的基类包含一个指向成员函数的函数指针。如何从派生类中调用此成员函数?我想用它的指针调用这个函数。 到目前为止,这是我的代码:

#include <iostream>

class Base
{
public:
    Base()          {FuncPtr = &Base::Func1;}
    Base(int num)   {
        if(num==1)
            FuncPtr = &Base::Func1;
        else if(num==2)
            FuncPtr = &Base::Func2;
        else
            FuncPtr = NULL;
    }
protected:
    void (Base::*FuncPtr)(float ,float );

    void Func1(float x,float y) { std::cout << "Func1 called\n";}
    void Func2(float x,float y) { std::cout << "Func2 called\n";}
};

class Derived : private Base
{
public:
    Derived()                       {}
    Derived(int num) : Base(num)    {}

    void callBaseFunc1      (float x,float y) { this->Func1     (x,y);} // works
    void callBaseFuncViaPtr (float x,float y) { this->(*FuncPtr)(x,y);} // wrong ...
};

int main()
{
    Derived Test;

    Test.callBaseFunc1      (2.72f,3.14f);  // works
    Test.callBaseFuncViaPtr (2.72f,3.14f);  // syntax error in function declaration...

    getchar();
    return 0;
}

由于

1 个答案:

答案 0 :(得分:2)

你几乎拥有它,只是移动parens:

void callBaseFuncViaPtr (float x,float y) { (this->*FuncPtr)(x,y);}