下面的示例显示了将虚拟成员函数绑定到fn的基类。在gcc 4.8上,对派生类的fn的调用将调用重载的calculate函数。谁能解释为什么会这样?此行为编译器是否独立运行?
#include <functional>
#include <iostream>
class Base {
public:
Base(){
fn = std::bind(&Base::calculate,this,1);
}
virtual int calculate(int value){
return value + 1;
}
std::function<int(int)> fn;
};
class Derived : public Base {
public:
Derived() : Base() {}
int calculate(int value){
return 0;
}
};
int main(int argc, const char **argv){
Derived test;
std::cout << test.fn(10) << std::endl;
/* Output of test.fn(10) is zero, so overloaded function was called */
return 0;
}
代码的行为符合预期:调用虚拟成员函数将分派到包含调用实例对象的最派生对象中最被重写的函数。您正在使用成员函数指针(在bind表达式内部)的事实没有任何区别。实际上,指向成员函数的指针的全部要点是它们可以正确地与虚拟分派一起使用。
如果要对基函数进行非虚拟调用,则可以执行以下操作:
Base() : fn([this]() { return this->Base::calculate(1); }) {}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句