zoukankan      html  css  js  c++  java
  • 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);  
        }
    }
  • 相关阅读:
    [CF1076D] Edge Deletion
    [CF1081D] Maximum Distance
    [CF1095F] Make It Connected
    [CF1328E] Tree Queries
    [CF1328F] Make k Equal
    Codeforces Round #629 (Div. 3) 总结
    [CF1131D] Gourmet choice
    [CF1176D] Recover it!
    [CF1205B] Shortest Cycle
    [CF1213G] Path Queries
  • 原文地址:https://www.cnblogs.com/yangyuliufeng/p/10720417.html
Copyright © 2011-2022 走看看