【问题标题】:Pointers to a virtual member functions [duplicate]指向虚拟成员函数的指针[重复]
【发布时间】:2015-05-12 16:20:57
【问题描述】:

考虑下面的代码

class BASE
{
  public:
            virtual void test_f(){std::cout<<"BASE::test_f\n";}
};

class DERIVED:public BASE
{
    public:
            virtual void test_f(){std::cout<<"DERIVED::test_f\n";}
};

void (BASE::*p_base)() = &BASE::test_f;

p_base 是指向类成员函数的指针,但它是多态的。 这意味着

DERIVED a;
(a.*p_base)();

将打印 DERIVED::test_f

如何获取指向基类的 test_f 的指针以进行 NON 多态调用?

【问题讨论】:

  • 你为什么要创建一个指向多态函数的指针?对我来说没有太大意义。
  • 是的,我知道。我只是好奇这些事情是如何运作的。

标签: c++ pointers pointer-to-member


【解决方案1】:

例子:

#include <iostream>
#include <functional>

class BASE
{
  public:
            virtual void test_f(){std::cout<<"BASE::test_f\n";}
};

class DERIVED:public BASE
{
    public:
            virtual void test_f(){std::cout<<"DERIVED::test_f\n";}
};

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 2015-12-17
    • 2011-07-01
    • 2015-06-28
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2010-11-08
    相关资源
    最近更新 更多