2013-11-04 92 views
0

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

+0

也只是爲了澄清其他兩個文件simpson7.h和simpson7.cpp所以不是原因 – taylor

回答

4

如果你看一下頭文件,你有這樣的聲明

template <typename mytype> 
double SimpsonIntegration(double (*functocall)(double) ,int bin, double a, double b); 

和源文件中你有

double SimpsonIntegration(double (*functocall)(double), int bin, double a, double b) 

這是不相同的功能。編譯器會嘗試搜索非模板函數,但尚未聲明,因此會出現錯誤。

簡單的解決方案是刪除頭文件中的模板規範。

如果你希望函數是一個模板函數,那麼你應該小心分離的聲明和定義,請參閱this old question

+0

非常感謝你的工作!這麼簡單的事情!感謝您幫助這位初學者! – taylor

+0

我遇到另一個錯誤,說「鏈接器命令失敗,退出代碼1」 – taylor

+0

@泰勒這可能是另一個問題,因此可能需要一個新的問題。你應該做的是在問題中發佈* complete *和* unedited *錯誤日誌,並且只發布相關行(即錯誤消息指示的行或者錯誤消息中提到的符號的用法)。 –