好吧,所以我对C++比较新,我想弄清楚如何使用函数指针。我有一个函数,它是一个简单的数值积分,我试图传递给它哪个函数进行整合,以及整合的限制是什么。我在Xcode中这样做,错误是在主代码中说“没有匹配函数调用SimpsonIntegration”。如果有人可以请帮助,我将不胜感激。此外,由于我正在学习,任何其他批评也将受到赞赏。 main.cpp函数如下。无法将函数指针传递给头文件中声明的函数
#include <iostream>
#include "simpson7.h"
#include <cmath>
using namespace std;
int main(int argc, const char * argv[])
{
double a=0;
double b=3.141519;
int bin = 1000;
double (*sine)(double);
sine= &sinx;
double n = SimpsonIntegration(sine, 1000, 0, 3.141519);
cout << sine(0)<<" "<<n;
}
的simpson.h文件如下:
#ifndef ____1__File__
#define ____1__File__
#include <iostream>
template <typename mytype>
double SimpsonIntegration(double (*functocall)(double) ,int bin, double a, double b);
extern double (*functocall)(double);
double sinx(double x);
#endif /* defined(____1__File__) */
的simpson.cpp文件是下一个:
#include "simpson7.h"
#include <cmath>
#include <cassert>
//The function will only run if the number of bins is a positive integer.
double sinx(double x){
return sin(x);
}
double SimpsonIntegration(double (*functocall)(double), int bin, double a, double b){
assert(bin>0);
//assert(bin>>check);
double integralpart1=(*functocall)(a), integralpart2=(*functocall)(b);
double h=(b-a)/bin;
double j;
double fa=sin(a);
double fb=sin(b);
for (j=1; j<(bin/2-1); j++) {
integralpart1=integralpart1+(*functocall)(a+2*j*h);
}
for (double l=1; l<(bin/2); l++) {
integralpart2=integralpart2+(*functocall)(a+(2*l-1)*h);
}
double totalintegral=(h/3)*(fa+2*integralpart1+4*integralpart2 +fb);
return totalintegral;
}
好吧好吧,现在我固定的愚蠢的错误,我试图编译我得到这个错误:“链接器命令失败,退出代码1”。
也只是为了澄清其他两个文件simpson7.h和simpson7.cpp所以不是原因 – taylor