我有两个功能:
char* odwroc(char* nap, int n)
char* male(char* nap, int n)
我已经定义了一个指向那种函数的指针
typedef char*(*pointerToFunction )( char*, int );
然后在main中使用了这个定义:
pointerToFunction ptr1 = odwroc;
pointerToFunction ptr2 = male;
但是现在我必须创建一个函数,作为第一个参数获取指向函数的数组的数组,我被卡住了。我不知道如何定义函数指针数组以及modyfikuj
参数列表的外观。
void modyfikuj(char* pointerToFunction *pointerArray, int length, char* nap2, int n){
}
答案 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 :(得分:1)
即使上面的答案有意义,使用诸如std :: vector之类的容器会在传递类似类型的数组(如指向函数的指针)时提供更多控制。请尝试以下代码段。
#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;
}