C++ 从基类调用重写的方法
在下面的场景中,如何从基类调用重写的C++ 从基类调用重写的方法,c++,C++,在下面的场景中,如何从基类调用重写的bar方法 有一个要求,回调应该始终调用方法foo,该方法应该调用被最新派生类覆盖的bar #include <iostream> #include <functional> #include <typeinfo> using namespace std; std::function<void(void)> callback = nullptr; class Base { public: Base(B
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;
}
#包括
#包括
#包括
使用名称空间std;
std::function callback=nullptr;
阶级基础{
公众:
Base(Base*ptr){callback=std::bind(&Base::foo,*ptr);}
虚拟~Base(){}
虚拟void foo(){
bar();//如何从派生而不是基调用foo()?
}
virtual void bar(){cout您将virtual方法与派生对象绑定不正确,正在切片派生对象。请尝试此操作(*已删除)
一种完全避免std::bind()
的替代方法:
Base(Base*ptr){
回调=[this](){foo();};
}
请注意,这至少需要C++11
Base(Base *ptr){
callback = std::bind(&Base::foo, ptr);
}