Calling a member function using function pointers from another class's instance

馋奶兔 提交于 2019-12-02 17:00:45

问题


#include<iostream>
#include<conio.h>
using namespace std;
class Base;
typedef void (Base::*function)();
class Base
{
public:
    function f;
    Base()
    {
        cout<<"Base Class constructor"<<endl;
    }
    virtual void g()=0;
    virtual void h()=0;
};
class Der:public Base
{
public:
    Der():Base()
    {
        cout<<"Derived Class Constructor"<<endl;
        f=(function)(&Der::g);
    }
    void g()
    {
        cout<<endl;
        cout<<"Function g in Derived class"<<endl;
    }
    void h()
    {
        cout<<"Function h in Derived class"<<endl;
    }
};
class Handler
{
    Base *b;
public:
    Handler(Base *base):b(base)
    {
    }
    void CallFunction()
    {
        cout<<"CallFunction in Handler"<<endl;
        (b->*f)();
    }
};
int main()
{
    Base *b =new Der();
    Handler h(b);
    h.CallFunction();
    getch();
}

I am getting an error while trying to call a member function in a derived class using function pointer declared in the base class. The function pointer is declared public and is actually used by another class Handler. I have used an unsafe typecast in this code. (function)(&Der::g). Is there any way to avoid it?


回答1:


f doesn't appear to be in scope in Handler::CallFunction. I'm guessing you meant to call the b->f using b as this, as it (b->*(b->f))(). When I make this change, your code compiles and prints out something sane.



来源:https://stackoverflow.com/questions/14332600/calling-a-member-function-using-function-pointers-from-another-classs-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!