函数指针作为参数的 C++ 问题

标签 c++ function pointers

我正在尝试在 C++ 中应用 newtons 方法,现在只是测试我的指针是否有效且正确。现在的问题是它无法调用函数来测试它,它说转换存在问题。

我的代码:

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

double newton(double (*f) (double), double (*fPrime)(double), double intialValue, int    iterations);
double f(double x);
double fPrime(double x);

int main() {


int limitIterations = 0;
double intialValue = 0;


cout << "Please enter a starting value for F(X): " ;
cin >> intialValue;

cout << endl << "Please enter the limit of iterations performed: " ;
 cin >> limitIterations;



cout << newton(intialValue, limitIterations);


return 0;
}

 double f(double x) {
 double y;
 y =(x*x*x)+(x*x)+(x);
 return (y);
 }

double fPrime(double x){
double y;
y = 3*(x*x) + 2 * x + 1;
return (y);

}

double newton(double (*f) (double), double (*fPrime)(double), double intialValue, int     iterations){

    double approxValue = 0;

    approxValue = f(intialValue);

    return (approxValue);

 }

错误:

|26|error: cannot convert 'double' to 'double (*)(double)' for argument '1' to 'double  newton(double (*)(double), double (*)(double), double, int)'|

最佳答案

如果你确实想声明 newton 来获取函数指针,那么你需要在调用站点将它们传递给 newton:

cout << newton(f, fPrime, initialValue, iterations);

编译器的错误只是说你在它期望函数指针的槽中传递了一个 double 并且它不知道如何转换一个 double 进入函数指针 double (*)(double)

关于函数指针作为参数的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22775300/

相关文章:

c++ - C/C++ 结构体中的指针

c++ - 如何通过c++获取图像的所有像素数据(RGB)

javascript - 递归requestAnimationFrame() javascript循环直接跳到最后

c++指向 vector 内部 float 的指针

c++ - sizeof() : the size of a class isn't the same as the size of it's members together?

c - 无效的目的*

c++ - 具有可变参数类型的模板多重可变继承

c++ - 具有商业产品灵活许可证的免费 C++ ZIP 解析器?

javascript - javascript中 "click"事件的嵌套函数调用

教程