我想使用成员函数指针调用虚函数的基类实现。
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 的成员函数指针,或者我必须以某种方式使用 using
?
在我的实际应用程序中,我使用 boost::bind 在 callFunc 中创建了一个 boost::function 对象,稍后我用它来从程序的另一部分调用 func。因此,如果 boost::bind 或 boost::function 有某种解决此问题的方法也会有所帮助。
最佳答案
当您通过引用或指针调用虚拟方法时,您将始终激活虚拟调用机制以找到最派生的类型。
最好的办法是添加一个非虚拟的替代函数。
关于c++ - 用函数指针调用虚成员函数的基类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1207106/