简体   繁体   中英

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.

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

//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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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