c++函数指针

假如需要定义一个fp指针,可以指向任何返回类型为double、参数类型为int的函数
方法为:
double (*fp)(int);
或者:
typedef double (*FP)(int); 
Fp fp;
一般用&取函数首地址赋值给fp。如果省略&,编译器会自动把函数名隐式类型转换成函数首地址
 
调用方法如下:
#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 << "请输入要计算的函数!";
        cin >> index;
    }while(index<0 || index>7);
    cout << "请输入参数:";
    cin >> x;
    cout << "结果为:" <<(*func_list[index])(x)<<endl;
    return 0;
}
调用时(*func_list[index])(x)可以直接写成func_list[index](x)
此外,还可以把函数指针作为参数传递给另一个函数:
template <class T>
void BinaryTree<T>::PreOrder(void (*visit)(BinTreeNode<T> *p)){
    stack<BinTreeNode<T>*> S;
    BinTreeNode<T> *p=root;
    S.Push(NULL);
    while(p!=NULL){
        visit(p);
        if(p->rightChild!=NULL) S.Push(p->rightChild);
        if(p->leftChild!=NULL) p=p->leftChild;
        else S.Pop(p);  
    }
}

转载于:https://www.cnblogs.com/yangyuliufeng/p/10720417.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值