简体   繁体   English

从基础 class 调用重写的方法

[英]Call overridden method from base class

How to call overridden bar method from base class in the following scenario?在以下场景中,如何从基础 class 调用覆盖的bar方法?

There is requirement that callback should always call method foo which should call bar which is overridden by latest derived class.要求回调应始终调用方法foo ,该方法应调用bar ,该方法被最新派生的 class 覆盖。

#include <iostream>
#include <functional>
#include <typeinfo>

using namespace std;

std::function<void(void)> callback = nullptr;

class Base {
 public:
  Base(Base* ptr) { callback = std::bind(&Base::foo, *ptr); }

  virtual ~Base() {}

  virtual void foo() {
    bar();  // How call foo() from Derived instead of Base?
  }
  virtual void bar() { cout << "Base::bar" << endl; }
};

class Derived : public Base {
 public:
  Derived() : Base(this) {}

  virtual void bar() override { cout << "Derived::bar" << endl; }
};

int main() {
  cout << "Hello World" << endl;
  Base* b = new Derived();

  cout << "**callback**" << endl;
  callback();  // output should be 'Derived::bar'

  return 0;
}

You are binding the virtual method with the derived object improperly, slicing the derived object.您将虚拟方法与派生的 object 绑定不正确,从而对派生的 object 进行切片。 Try this (* is removed)试试这个(* 已删除)

Base(Base *ptr){
    callback = std::bind(&Base::foo, ptr);
}    

An alternative method that avoids std::bind() altogether:另一种完全避免std::bind()的方法:

Base(Base *ptr){
        callback = [this]() { foo(); };
    }

https://godbolt.org/z/pEs9ta https://godbolt.org/z/pEs9ta

Note that this requires at least C++11.请注意,这至少需要 C++11。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM