c++:函数指针数组



假设我们有两个函数

foo() { cout << "Hello"; }
foo2() { cout << " wolrd!"; }

我如何创建一个指针数组(说a,b),a指向foo()b指向foo2()?我的目标是将这些指针存储在数组A中,然后循环遍历A来执行这些函数。

可以这样使用类型化函数指针:

using FunPtrType = void(*)();
FunPtrType arr[]{&foo,  &foo2};
// or
std::array<FunPtrType, 2> arr2{&foo,  &foo2};
// ... do something with the array of free function pointers
// example
for(auto fun: arr2)
fun();

有一个简单的实现:

#include <iostream>
#include <vector>
using namespace std;
// Defining test functions
void a(){cout<<"Function A"<<endl;}
void b(){cout<<"Function B"<<endl;}
int main()
{
/*Declaring a vector of functions 
Which return void and takes no arguments.
*/
vector<void(*)()> fonc;
//Adding my functions in my vector
fonc.push_back(a);
fonc.push_back(b);
//Calling with a loop.
for(int i=0; i<2; i++){
fonc[i]();
}
return 0;
}

现在已经不需要typedefs了,只要使用auto就可以了。

#include <iostream>
void foo1() { std::cout << "Hello"; }
void foo2() { std::cout << " world!"; }
auto foos = { &foo1, &foo2 };
int main() { for (auto foo : foos) foo(); }

有两种相同的方法做你想做的事:

方法1


#include <iostream>
void foo() 
{ 
std::cout << "Hello";
}
void foo2() 
{ 
std::cout << " wolrd!"; 

}

int main()
{

void (*a)() = foo;// a is a pointer to a function that takes no parameter and also does not return anything

void (*b)() = foo2;// b is a pointer to a function that takes no parameter and also does not return anything


//create array(of size 2) that can hold pointers to functions that does not return anything and also does not take any parameter
void (*arr[2])() = { a, b};

arr[0](); // calls foo 

arr[1](); //calls foo1

return 0;
}

方法1可以在这里执行。

方法2


#include <iostream>
void foo() 
{ 
std::cout << "Hello";
}
void foo2() 
{ 
std::cout << " wolrd!"; 

}

int main()
{

//create array(of size 2) that can hold pointers to functions that does not return anything
void (*arr[2])() = { foo, foo2};

arr[0](); // calls foo 

arr[1](); //calls foo1

return 0;
}

方法2可以在这里执行。

最新更新