[英]Error when using a function as an argument of a function
I'm trying to create a program to numerically integrate a function between two limits. 我正在尝试创建一个程序,以数字方式将两个极限之间的函数进行积分。 I've created a minimal example (where the "integral" is always 1.0) to illustrate an error I get.
我创建了一个最小的示例(其中“积分”始终为1.0)来说明出现的错误。 The code below tries to use a function whose arguments are two doubles and a function from doubles to doubles:
下面的代码尝试使用参数为两个double的函数和一个从double到double的函数:
#include <iostream>
#include <math.h>
double cons(double a, double b, double c(double d))
{
return 1.0;
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f(x));
std::cout << I << "";
}
This results in an error on cpp.sh : 这会导致cpp.sh出现错误:
14:31: error: cannot convert 'double' to 'double ( )(double)' for argument '3' to 'double cons(double, double, double ( )(double))'
14:31:错误:无法将参数'3'的 'double'转换为'double( )(double)'到'double cons(double,double,double( )(double))'
Obviously, the difference between doubles and double-valued functions is causing a problem here. 显然,双精度和双值函数之间的差异在这里引起了问题。 How can I get this working?
我该如何工作?
You need to pass the function, not call it. 您需要传递函数,而不是调用它。
#include <iostream>
#include <math.h>
double cons(double a, double b, double c(double d))
{
return 1.0;
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f);
std::cout << I << "";
}
You didn't pass a function but the result of a function, a double. 您没有传递函数,而是传递函数的结果,即double。 Second, you didn't correctly declared a function pointer as argument.
其次,您没有正确地将函数指针声明为参数。
If you want to pass a double then declare a double as argument: 如果要传递一个double,则将double声明为参数:
double cons(double a, double b, double c)
{
return 1.0*a*b*c;
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f(x));
std::cout << I << "";
}
If you want to pass a function (aka function pointer as C++ is not a functional language): 如果要传递函数 (又称函数指针,因为C ++不是函数语言):
double cons(double a, double b, double (*c)(double d))
{
return 1.0*c(a);
}
double f(double x)
{
return x*x;
}
int main()
{
double x;
double I = cons(0, 1, f);
std::cout << I << "";
}
Your problem in this case is that you are calling the function with: 在这种情况下,您的问题是您使用以下方法调用该函数:
double I = cons(0, 1, f(x));
so you actually give cons the return value of f() instead of the actual function. 因此,您实际上给了cons f()的返回值,而不是实际的函数。 So you need to write this insteed:
因此,您需要编写以下说明:
double I = cons(0, 1, f);
As an alternativ you could also use lambda expressions for your problem. 作为替代方案,您也可以使用lambda表达式解决问题。 For example something like this:
例如这样的事情:
#include <iostream>
#include <math.h>
#include <functional>
double cons(double a, double b, const std::function<double(double)>& callback)
{
// do something
}
int main()
{
double x;
double I = cons(0, 1, [](double x){ return x*x});
std::cout << I << "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.