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);  
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM