[英]Array of pointers to functions C++
我有3個具有相同簽名的功能。 我需要使用指向函數的指針來初始化數組。 我有:
typedef void(*sorting_func) (int* a, int n);
和功能:
class Sortings {
public:
static void bubble_sort(int a[], int n);
static void bubble_aiverson_1(int a[], int n);
static void bubble_aiverson_2(int a[], int n);
};
我需要在此類中使用帶有指針的數組來像這樣使用:
Sortings::array[0]...
函數不能是靜態的。
您可以使用std::function
的vector
,即
std::vector<std::function(void(int*,int)>> sortingFunctions;
然后,根據情況,您可以直接向后推自由函數,或使用lambda通過以下方式向后推成員函數:
//Capturing `this` in the lambda implies the vector is a member of the class
//Otherwise, you must capture an instance of the class you want to call the
//function on.
std::function<void(int*,int)> myMemberFunction = [this](int* a, int n){
this->memberFunction(a,n);
}
sortingFunctions.push_back(myMemberFunction);
假設您在Sorting
類的成員函數中創建矢量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.