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