无法将函数指针传递给头文件中声明的函数
Cannot pass function pointer to function declared in header file
好的,所以我对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)
这不是同一个功能。编译器尝试搜索非模板函数,但尚未声明该函数,因此会给出错误。
简单的解决方案是删除头文件中的模板规范。
如果你确实希望函数是一个模板函数,那么你应该小心声明和定义的分离,例如这个老问题。
相关文章:
- 用C++在单独的头文件中完成函数体
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 头文件、宏和内联函数c++
- 如何使用单独文件中的派生类访问友元函数对象
- C++无法定义虚拟函数 OUTER 类和头文件
- 回溯C++不打印函数,因此文件
- 如何从另一个文件继承私有成员变量和公共函数
- 从函数角度看ID到文件路径的内部与外部映射
- 区分非成员函数和头文件中的成员函数
- 如何使用对C函数和类对象的外部调用来处理C++头文件
- 如何在其他文件中使用函数
- 整数键映射到头文件中的成员函数指针
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 用"=default"声明的函数应该只在头文件中执行
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- C++ - 在一个函数/文件中初始化变量然后在main()/另一个文件中使用它的最佳方法是什么?
- C++单独的函数文件
- 只对单个函数/文件启用编译器优化