C++指向函数动态数组的指针

C++ Pointer to Dynamic Array of functions?

本文关键字:数组 指针 动态 函数 C++      更新时间:2023-10-16

我创建了一个指向函数的指针数组,我想知道是否可以动态创建指针数组,正如您在下面看到的,我想动态更改数组长度,目前为 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()ntThe value is: " << n << endl;
}
void func2(int n)
{
    cout << "In func2()ntThe 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;
}