假設我們有 2 個函式
foo() { cout << "Hello"; }
foo2() { cout << " wolrd!"; }
如何建立指標(比如陣列a,b),有a指向foo()和b到foo2()?我的目標是將這些指標存盤在陣列 A 中,然后遍歷 A 以執行這些函式。
uj5u.com熱心網友回復:
您可以按如下方式使用型別化函式指標:
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();
uj5u.com熱心網友回復:
有一個簡單的實作:
#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;
}
uj5u.com熱心網友回復:
這些天不需要 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(); }
uj5u.com熱心網友回復:
有兩種等效的方法可以執行您想要的操作:
方法一
#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可以在這里執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/329665.html
