C++ 变量在传递给函数时丢失值

标签 c++ c++11 lambda

我正在创建程序来计算数学表达式 ax^2 + b*x + ca,b,c 被传递给 quadraticExp()xquadraticExp(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 , bc , 在 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/

相关文章:

c++ - 程序崩溃并显示 0xC000000D 并且没有异常 - 我该如何调试它?

c++ - 如何在 C++ 中从控制台读取整数而不添加换行符?

C++ 位集引用

java - 如何将 Java 8 Stream 转换为二维数组?

c# - 为什么 IQueryable 后面跟着 Any 会导致选择没有Where 子句?

c# - List<T> 的自定义排序

c++ - 将自定义 HTML 类属性添加到 QTextEdit 中的选定 block

c++ - Derived对象调用Base方法的模板推导

c - 读取内部具有不同字节长度值的二进制文件

c++ - 用于 C++ 的 XSLT 2.0 库