指向参数减少的函数的指针

时间:2014-03-14 18:26:39

标签: c++ arguments function-pointers

我遇到了函数指针的问题:

我需要在数值上集成一个函数,因此需要将一个带有该函数的指针传递给"积分器"。问题是,要集成的函数只需要一个参数。类似的东西:

double f(int i, double x){ // i to switch the function, x to evaluate
  if(i==1) {return sin(x);}
  if(i==2) {return exp(x);}
}

double integrate(double (*function)(double), double x0, double x1){
//integrate the passed *function from x0 to x1
}

int main(){
  int i=1; // i want to chose sin(x)
  cout << integrate(&f, 0, 5);
}

我怎样才能修复一个论点而只是对剩下的?谢谢你的帮助!

PS。在我需要搜索什么,关键字是什么,以及面向对象编程的视角?

1 个答案:

答案 0 :(得分:1)

这应该这样做......

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;

typedef double (*f_ptr)(double);

double f_sin_x(double x); 
double f_exp_x(double x); 
f_ptr fchoice(int i);
double integrate(double x0, double x1, double(*function_to_call)(double));

const int num_steps = 100;

int main()
{
    double x0(0.0), x1(1.0);
    int mychoice = 2;
    cout << "Integration Result: "
         << integrate(x0, x1, fchoice(mychoice)) << endl;
    return 0;
}

double f_sin_x(double x) {return sin(x);}
double f_exp_x(double x) {return exp(x);}

f_ptr fchoice(int i)
{
    if(i == 1) {return &f_sin_x;}
    else return &f_exp_x;
}

double f(int i, double x)
{
    if(i==1)
        return sin(x);
    else
        return exp(x);
}

double integrate(double x0, double x1, double(*function_to_call)(double))
{
    double dx = (x1 - x0)/num_steps; 

    double result = 0.0;
    for (int i = 0; i < num_steps; i++)
    {
        result += function_to_call(x0 + dx); 
    }

    return result;
}