BP-5-8 Pointer for a Function

Chapter 05 Compound Data Type - Constructed Type

5.5 Pointer for a Function
  • Definition

    <return-type> (*<pointer>) (<parameter-list>);
    //or
    typedef <return-type> (*<type-name>) (<parameter-list>);
    <type-name> <pointer>;
    
  • Call using a Pointer

    (*<function-pointer>)(<argument-list>);
    //or
    <function-pointer>(<argument-list>);
    
  • Assignment

    fp = &f; //we can use & to get the address of a function
    //or
    fp = f; //the compiler will convert the name of a function into an address implicitly
    

Example:

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

const int MAX_LEN = 8;
typedef double (*FP) (double);
FP func_list[MAX_LEN] = {sin, cos, tan, asin, acos, atan, log, log10};

int main(){
    int index;
    double x;
    do{
        cout << "Please input the function you want to compute (0:sin 1:cos 2:tan 3:asin" << endl;
        cout << "4:acos 5:atan 6:log 7:log10):";
        cin >> index;
    } while (index < 0 || index > 7);
    cout << "Please input the argument:";
    cin >> x;
    cout << "The outcome is:" << (*func_list[index])(x) << endl;
    return 0;
}
  • Pass a function to another function

Juse refer to the higher-order function we’ve learnt in Python, and combine it with call-by-reference, you will understand the working principle for the functional pointer passing a function. The following example will show the process.

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

const int N = 1e6;

double Integrate(double (*pfun)(double x), double x1, double x2) {
    double s = 0;
    int i = 1, n;
    while(i <= n){
        s += (*pfun)(x1 + (x2 - x1) / n * i);
        ++i;
    }
    s *= (x2 - x1) / n;
    return s;
}
double square(double x){
    return x * x;
}

int main(){
    cout << Integrate(cos, 1, 2) << endl;
    cout << Integrate([](double x)->double {return x * x}, 0, 1) << endl; //lambda expression for anonymous function
    cout << Integrate(square, 0, 1) << endl;
    return 0;
}

Since we’ve make it clear that pointer is also a kind of data type, it is stored in the memory with a unique address, which indicates that we can use anothor pointer to point at it and use the third pointer to point at this one. As a result, we will get higher-order pointer.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值