【问题标题】:Is it possible to obtain a pointer to the definition of a pure virtual function? [duplicate]是否可以获得指向纯虚函数定义的指针? [复制]
【发布时间】:2012-04-27 19:14:58
【问题描述】:

可能重复:
Calling base class definition of virtual member function with function pointer

给定以下层次结构:

struct Base
{
  virtual void f() = 0;
};

void Base::f()
{
  cout << "Base::f\n";
}

struct Derived : Base
{
  void f()
  {
    cout << "Derived::f\n";
  }
};

我们可以像这样强制调用Base::f

Derived d;

d.Base::f();

或:

Base * b = &d;

b->Base::f();

那里没有惊喜。但是有没有可能得到一个可以调用Base::f的成员函数指针呢?

void (Base::*bf)() = &Base::f;

for_each( b, b+1, mem_fn( bf ) ); // calls Derived::f

(为了记录,我实际上不需要这样做。我只是好奇。)

【问题讨论】:

    标签: c++ virtual-functions member-function-pointers pure-virtual


    【解决方案1】:

    正如 James McNellis 所说,简短的回答是“不”。

    更长的答案是,“如果你愿意接受一些正式的 UB,那么”:

    #include <iostream>
    #include <algorithm>    // for_each
    #include <functional>      // mem_fn
    using namespace std;
    
    struct Base
    {
      virtual void f() = 0;
    };
    
    void Base::f()
    {
      cout << "Base::f\n";
    }
    
    struct Derived : Base
    {
      void f()
      {
        cout << "Derived::f\n";
      }
    };
    
    int main()
    {
        struct DirtyHack: Base
        {
            void baseF() { Base::f(); }
        };
    
        Derived d;
        void (Base::*bf)() = static_cast< void(Base::*)() >( &DirtyHack::baseF );
        Base* b = &d;
    
        (b->*bf)();
        for_each( b, b+1, mem_fn( bf ) ); // calls Base::f
    }
    

    我不会这样做,但是我通常不会使用原始成员函数指针(绑定的指针是另一回事,例如对于 GUI 事件)。

    请注意,如果您控制 Base 类,那么您可以只分解出您希望不可被覆盖的功能。

    【讨论】:

    • +1 为我的噩梦提供新材料。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多