从基类调用重写的方法
Call overridden method from base class
在以下情况下如何从基类调用重写的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);
}
一种完全避免std::bind()
的替代方法:
Base(Base *ptr){
callback = [this]() { foo(); };
}
https://godbolt.org/z/pEs9ta
请注意,这至少需要 C++11。
相关文章:
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 方法重写线程C++中的概念
- 如何强制从重写方法调用重写的方法基方法?
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 在 C++ 中使用模板方法重写类方法
- 检查子类是否执行了方法重写
- C++方法重写和重载(编译器级别)
- 用模板方法重写虚拟方法
- 方法重写(没有虚拟方法或指针)是否被认为是多态性的一部分
- C++ - 方法重写未按预期表示
- 使用两种方法重写<<运算符
- C++阻止方法重写
- C++方法重写
- c++在具体类中强制方法重写
- 方法重载和方法重写的性能问题
- C++中的方法重写是否总是在派生类的标头中完成?
- 是否有更好的方法重写此代码片段
- 为什么静态方法重写基类非静态方法
- 方法重写