[英]C++: array of pointers to functions
假設我們有 2 個函數
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;
}
這些天不需要 typedef,只需使用auto
。
#include <iostream>
void foo1() { std::cout << "Hello"; }
void foo2() { std::cout << " world!"; }
auto foos = { &foo1, &foo2 };
int main() { for (auto foo : foos) foo(); }
有兩種等效的方法可以執行您想要的操作:
方法一
#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可以在這里執行。
方法二
#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可以在這里執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.