首页 > 解决方案 > 将元素分配给函数类型向量的问题(作为对象的函数)

问题描述

我正在关注本教程,并在其中使用函数作为对象进行介绍。我有以下代码:

double multby2(double num) {
    return num * 2;
}

double multby3(double num) {
    return num * 3;
}

int main()
{

auto times2 = multby2; //store function as variable 
 cout << "5 * 2 = " << times2(5) << endl; //so here times2 becomes multby2. I guess an object of it?
 vector<function<double(double)>> funcs(2); //vector that takes type dbl func with element size of 2
        funcs[0] = multby2(10);
        funcs[1] = multby3;
        cout << "2 * 10 = " << funcs[0](10) << endl;
}

当我尝试编译funcs[0] = multby2(10);时,它给了我错误:

Error C2679 binary '=': no operator found which takes a right-hand operand of type 'double' (or there is no acceptable conversion

怎么会这样?我怎么能做,cout << "2 * 10 = " << funcs [0] (10) << endl;但不能绕过这一步,只是multby(2)像我试图在 at 那样分配一个参数并将其放入向量中funcs[0] = multby2(10)。您还会注意到我可以做到,cout << "5 * 2 = " << times2(5) << endl;我认为我可以遵循相同的想法,只需在向量元素分配中插入要相乘的双精度数。

标签: c++

解决方案


推荐阅读