我正在创建程序来计算数学表达式 ax^2 + b*x + c
,a,b,c
被传递给 quadraticExp()
和 x
从 quadraticExp(a,b,c)(x)
传递。
#include<iostream>
#include<functional>
#include<cmath>
auto quadraticExp(double a, double b, double c) -> std::function<double(double)>
{
//return auto f1 [&] (double x) -> double
return [&] (double x)
{
std::cout<<a<<" "<<b<<" "<<c<<" "<<x<<std::endl;
return ( a*std::pow(x,2) + b*x + c );
};
}
int main()
{
double a={1.0}, b={1.0}, c={1.0}, x={3.0} ;
std::cout<<quadraticExp(a,b,c)(x)<<std::endl;
return 0;
}
输出是:
1 8.00798e-307 1.83847e-307 3
9
- 所以变量
b,c
正在丢失它们的值。为什么会发生这种情况,我该如何摆脱它? - 我可以编写 lambda 对象的完整定义
//return auto f1 [&] (double x) -> double
以便我可以在函数中重用f1
吗?
最佳答案
So variables b,c are loosing their values. Why is this happening and how can I get rid of that?
尝试
// .....v
return [=] (double x)
{
std::cout<<a<<" "<<b<<" "<<c<<" "<<x<<std::endl;
return ( a*std::pow(x,2) + b*x + c );
};
我的意思是...如果你通过 a
, b
和 c
, 在 lambda 函数中,作为 references,它们在 quadraticExp()
时无效函数终止。因此,当您调用 lambda(quadraticExp()
之外)时,a
的值, b
, c
lambda 函数内部是未定义的。
您必须通过值 传递它们,即(为简单起见)使用[=]
而不是 [&]
.
Can I write full definition of lambda object //return auto f1 [&] (double x) -> double so I can reuse f1 in the function?
不确定是否理解...您的意思是这样的吗? [注意:代码未经测试]
auto quadraticExp (double a, double b, double c)
-> std::function<double(double)>
{
auto f1 = [=](double x)
{
std::cout<<a<<" "<<b<<" "<<c<<" "<<x<<std::endl;
return ( a*std::pow(x,2) + b*x + c );
};
f1(42); // use of f1 inside the function
return f1;
}
关于C++ 变量在传递给函数时丢失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48132218/