Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在基构造函数中绑定虚拟类成员函数_C++_Class_Bind_Class Method - Fatal编程技术网

C++ 在基构造函数中绑定虚拟类成员函数

C++ 在基构造函数中绑定虚拟类成员函数,c++,class,bind,class-method,C++,Class,Bind,Class Method,下面的示例显示了将虚拟成员函数绑定到fn的基类。在GCC4.8中,对派生类调用fn将调用重载的计算函数。有人能解释为什么会这样吗?这种行为是独立的吗 #include <functional> #include <iostream> class Base { public: Base(){ fn = std::bind(&Base::calculate,this,1); } virtual int calculate(i

下面的示例显示了将虚拟成员函数绑定到fn的基类。在GCC4.8中,对派生类调用fn将调用重载的计算函数。有人能解释为什么会这样吗?这种行为是独立的吗

#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;
}
#包括
#包括
阶级基础{
公众:
Base(){
fn=std::bind(&Base::calculate,this,1);
}
虚拟整数计算(整数值){
返回值+1;
}
std::功能fn;
};
派生类:公共基{
公众:
派生():基(){}
int计算(int值){
返回0;
}
};
int main(int argc,常量字符**argv){
衍生试验;

std::cout代码的行为与预期一致:调用虚拟成员函数将分派给包含调用实例对象的最派生对象中最重写的函数。事实上,您正在使用成员函数指针(在绑定表达式中)没有区别;事实上,指向成员函数的指针的全部意义在于,它们可以正确地使用虚拟分派

如果希望对基函数进行非虚拟调用,可以执行以下操作:

Base() : fn([this]() { return this->Base::calculate(1); }) {}

为什么不应该发生这种情况?表达式
&Base::calculate
是一个编译时常量-它的值不可能取决于使用它的上下文。通过此指针调用成员函数时,虚拟分派的方式与直接使用函数名时的方式相同。代码中没有任何重载.你是说“重写”吗?谢谢你的帮助。类成员绑定对我的应用程序非常有帮助。