2014-04-14 5 views
1

다른 함수에 함수 포인터의 배열을 전달합니다 :는 어떻게이 개 기능을 가지고있다

pointerToFunction ptr1 = odwroc; 
pointerToFunction ptr2 = male; 

하지만 지금은 첫 번째 매개 변수가 해당 포인터의 배열을 가져 오는 함수를 만들어야합니다. d 나는 붙어있다. 나는 함수에 대한 포인터의 배열을 정의하는 방법과 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

비록 위의 대답 감각, 이러한 표준 : : 벡터로 용기의 사용은 포인터로 당신에게 유사한 유형의 배열을 전달 더 컨트롤을 줄 것이다 만들기 함수로. 아래의 코드 스 니펫을 시도하십시오.

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