考虑以下代码
class BASE
{
public:
virtual void test_f(){std::cout<<"BASE::test_fn";}
};
class DERIVED:public BASE
{
public:
virtual void test_f(){std::cout<<"DERIVED::test_fn";}
};
void (BASE::*p_base)() = &BASE::test_f;
p_base是指向类成员函数的指针,但它是多态性的。这意味着
DERIVED a;
(a.*p_base)();
将打印派生:: test_f
我如何获取指向基类的test_f的指针以进行非多态性调用?
示例:
#include <iostream>
#include <functional>
class BASE
{
public:
virtual void test_f(){std::cout<<"BASE::test_fn";}
};
class DERIVED:public BASE
{
public:
virtual void test_f(){std::cout<<"DERIVED::test_fn";}
};
int main()
{
// prints Derived
void (BASE::*p_base)() = &BASE::test_f;
DERIVED a;
(a.*p_base)();
auto f = std::mem_fun(&BASE::test_f);
f(&a);
// prints Base
a.BASE::test_f();
auto callLater = [&a]() { a.BASE::test_f();};
callLater();
}