[英]C++ Pointer to Dynamic Array of functions?
我已經創建了一個指向函數的指針數組,我想知道是否可以動態創建指針數組,正如您在下面看到的那樣,我想動態更改數組長度,當前為2。
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void func1(int);
void func2(int);
int main()
{
void (*func[2])(int) = { &func1, &func2 };
func[0](10);
func[1](20);
cin.ignore();
return 0;
}
void func1(int n)
{
cout << "In func1()\n\tThe value is: " << n << endl;
}
void func2(int n)
{
cout << "In func2()\n\tThe value is: " << n << endl;
}
為函數類型創建一個typedef:
typedef void (*FunctionType)(int);
然后制作一個普通的動態數組:
FunctionType* func = new FunctionType[2];
然后,您可以分配:
func[0] = &func1;
並致電:
func[0](1);
動態更改數組大小的唯一方法是刪除指針,然后以適當的大小重新創建它。
//Placeholder
using Function = void(*)(int);
//We have 2 functions
Function* func = new Function[2];
//Assigning...
func[0] = &func1;
func[1] = &func2;
//Doing stuff...
//Oh no! We need a third function!
Function* newfunc = new Function[3]; //Create new array
newfunc[0] = func[0];
newfunc[1] = func[1]; //Better use a loop
newfunc[2] = &func3;
//Delete old array
delete func;
//Reassign to new array
func = newfunc;
//Now 'func' changed size :)
您可以使用std::vector
避免所有指針的使用:
//Placeholder
using Function = void(*)(int);
//Create std::vector
std::vector<Function> func{ &func1, &func2 }; //Default initialize with 'func1' and 'func2'
//Do stuff....
//Oh no! We need a third function
func.emplace_back(&func3);
//Now 'func' has 3 functions
希望下面的代碼對您有幫助:
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
void func1(int);
void func2(int);
int main()
{
std::vector<void(*)(int)> funcPointers;
funcPointers.push_back(&func1);
funcPointers.push_back(&func2);
funcPointers[0](10);
funcPointers[1](20);
cin.ignore();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.