无法将函数指针传递给头文件中声明的函数

Cannot pass function pointer to function declared in header file

本文关键字:函数 文件 声明 指针      更新时间:2023-10-16

好的,所以我对c ++相对较新,我正在尝试弄清楚如何使用函数指针。 我有一个函数,它是一个简单的数值积分,我正在尝试将要积分的函数以及积分的限制传递给它。 我在 Xcode 中执行此操作,错误出在主代码中,说"没有匹配函数来调用辛普森集成"。 如果有人能帮忙,我将不胜感激。 另外,由于我正在学习,任何其他批评也将受到赞赏。 主要.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__) */

接下来是辛普森.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"。

如果你看一下头文件,你有这个声明

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)

这不是同一个功能。编译器尝试搜索非模板函数,但尚未声明该函数,因此会给出错误。

简单的解决方案是删除头文件中的模板规范。

如果你确实希望函数是一个模板函数,那么你应该小心声明和定义的分离,例如这个老问题。