好吧,所以我對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