使用函数指针调用虚函数成员函数的基类定义 [英] Calling base class definition of virtual member function with function pointer

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

问题描述

我想使用成员函数指针调用虚函数的基类实现。

I want to call the base class implementation of a virtual function using a member function pointer.

class Base {
public:
    virtual void func() { cout << "base" << endl; }
};

class Derived: public Base {
public:
    void func() { cout << "derived" << endl; }

    void callFunc()
    {
        void (Base::*fp)() = &Base::func;
        (this->*fp)(); // Derived::func will be called.
                       // In my application I store the pointer for later use,  
                       // so I can't simply do Base::func().
    }
};

在上面的代码中,func的派生类实现将从callFunc调用。有没有办法我可以保存一个成员函数指针指向Base :: func,或者我必须使用使用以某种方式?

In the code above the derived class implementation of func will be called from callFunc. Is there a way I can save a member function pointer that points to Base::func, or will I have to use using in some way?

在我的实际应用程序中,我使用boost :: bind在callFunc中创建一个boost :: function对象,我稍后使用它从程序的另一部分调用func。所以如果boost :: bind或者boost :: function有一些方法来解决这个问题,这也有帮助。

In my actual application I use boost::bind to create a boost::function object in callFunc which I later use to call func from another part of my program. So if boost::bind or boost::function have some way of getting around this problem that would also help.

推荐答案

你通过引用或指针调用一个虚方法,你将总是激活找到最多派生类型的虚拟调用机制。

When you call a virtual method via a reference or a pointer you will always activate the virtual call mechanism that finds the most derived type.

你最好的办法是添加一个替代函数这不是虚拟的。

Your best bet is to add an alternative function that is not virtual.

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

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