bar
在以下情况下如何从基类中调用重写的方法?
要求回调应始终调用foo
应bar
被最新派生类覆盖的方法。
#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;
}
您将虚拟方法与派生对象绑定不正确,将派生对象切片。试试这个(*被删除)
Base(Base *ptr){
callback = std::bind(&Base::foo, ptr);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句