2014-04-14 50 views
1

我有兩個功能:如何通過函數指針陣列到另一個功能

char* odwroc(char* nap, int n) 
char* male(char* nap, int n) 

我已經定義了一個指針,它指向類型的功能

typedef char*(*pointerToFunction)(char*, int); 

然後在使用該定義在主要:

pointerToFunction ptr1 = odwroc; 
pointerToFunction ptr2 = male; 

但現在我必須創建一個函數,它作爲第一個參數獲取指針的數組,我被卡住了。我不知道如何定義指向函數的數組以及modyfikuj參數列表應該是什麼樣子。

void modyfikuj(char* pointerToFunction *pointerArray, int length, char* nap2, int n){ 
} 
+0

你會如何聲明一個參數作爲任何其他類型的數組?由於'pointerToFunction'是一個類型(實際上是一個類型的別名),它可以用作任何其他類型,比如'char'或'int'。 –

+0

@JoachimPileborg像這樣:'void modyfikuj(pointerToFunction * pointerArray,int length,char * nap2,int n){ }' – Yoda

+0

這看起來不錯。現在創建一個類型的數組,並將其傳遞給該函數。 –

回答

1

試試這個:

pointerToFunction mojefunkcje[] = { odwroc, male}; 

modyfikuj(mojefunkcje, ...);  // pass the array fo modyfikuj() 

void modyfikuj(pointerToFunction* funtab, ...) 
{ 
    funtab[0](string, liczba); // call odwroc(string, liczba) 
    funtab[1](string, liczba); // call male(string, liczba) 
} 
1

即使上面的回答是有意義的,使用的容器,如std ::矢量會給你傳遞相似類型的數組時,更多的控制權,如指針到一個功能。請嘗試下面的代碼片段。

#include "vector" 
using namespace std; 

typedef char*(*pointerToFunction)(char*, int); 

typedef vector<pointerToFunction> FUNCTION_VECTOR; 

bool modyfikuj(FUNCTION_VECTOR& vecFunctionVector) 
{ 
    // The below checking ensures the vector does contain at least one function pointer to be called. 
    if(vecFunctionVector.size() <= 0) 
    { 
     return false; 
    } 

    // You can have any number of function pointers to be passed and get it executed, one by one. 
    FUNCTION_VECTOR::iterator itrFunction = vecFunctionVector.begin(); 
    FUNCTION_VECTOR::const_iterator itrFunEnd = vecFunctionVector.end(); 
    char* cszResult = 0; 
    for(; itrFunEnd != itrFunction; ++itrFunction) 
    { 
     cszResult = 0; 
     // Here goes the function call! 
     cszResult = (*itrFunEnd)("Hello", 1); 

     // Check cszResult for any result. 
    } 

    return true; 

} 

char* odwroc(char* nap, int n); // You will define this function somewhere else. 
char* male(char* nap, int n); // You will define this function somewhere else. 

int main() 
{ 
    FUNCTION_VECTOR vecFunctions; 
    // You can push as many function pointers as you wish. 
    vecFunctions.push_back(odwroc); 
    vecFunctions.push_back(male); 
    modyfikuj(vecFunctions); 
    return 0; 
} 
相關問題