2013-11-04 94 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 *错误日志,并且只发布相关行(即错误消息指示的行或者错误消息中提到的符号的用法)。 –