使用来自另一个类的实例的函数指针调用成员函数 [英] Calling a member function using function pointers from another class's instance

查看:130
本文介绍了使用来自另一个类的实例的函数指针调用成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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();
}

尝试在派生类中调用成员函数时出错使用在基类中声明的函数指针。函数指针声明为public,实际上由另一个类Handler使用。我在这段代码中使用了不安全的类型转换。 (函数)(&安培;明镜::克)。有什么方法可以避免它吗?

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?

推荐答案

f 没有似乎在 Handler :: CallFunction 的范围内。我猜你打算用 b 打电话给 b-> f 作为这个,因为它(b-> *(b-> f))()。当我进行此更改时,您的代码会编译并打印出一些合理的内容。

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.

这篇关于使用来自另一个类的实例的函数指针调用成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆