简体   繁体   English

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

[英]C++ Pointer to Dynamic Array of functions?

I've created an array of pointer to functions, I want to know Is it possible to create array of pointer dynamically, as you see in below I want to change array length dynamically which currently is 2. 我已经创建了一个指向函数的指针数组,我想知道是否可以动态创建指针数组,正如您在下面看到的那样,我想动态更改数组长度,当前为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;
}

Make a typedef for the function type: 为函数类型创建一个typedef:

typedef void (*FunctionType)(int);

Then make a normal dynamic array: 然后制作一个普通的动态数组:

FunctionType* func = new FunctionType[2];

Then you can assign: 然后,您可以分配:

func[0] = &func1;

And call: 并致电:

func[0](1);

The only way to change the array size dynamically is to delete the pointer, and recreate it with the appropriate size. 动态更改数组大小的唯一方法是删除指针,然后以适当的大小重新创建它。

//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 :)

You would avoid all that pointer stuff using a std::vector : 您可以使用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

Hope below code will help you: 希望下面的代码对您有帮助:

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM