• 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);  
        }
    }
  • 相关阅读:
    ViewPager 滑动页(一)
    Fragment中Button的android:onClick 无法监听相应
    Button的四种Click响应方法
    环形图 自定义(一)
    Progress 自定义(一)-shape
    Button 自定义(一)-shape
    客户机页表遍历
    KVM的ept机制
    linux内核源码中两个重要的宏
    总结
  • 原文地址:https://www.cnblogs.com/yangyuliufeng/p/10720417.html
Copyright © 2020-2023  润新知