简体   繁体   English

如何动态创建函数数组?

[英]How to create array of functions dynamically?

What if i want to have an array of pointers to a function and the size of the array is not known from the beginning? 如果我想拥有一个指向函数的指针数组并且从一开始就不知道数组的大小,该怎么办? I'm just curious if there's a way to do that. 我只是好奇是否有办法做到这一点。 Using new statement or maybe something else. 使用新的声明或其他东西。 Something looking similar to 看起来很像的东西

void (* testArray[5])(void *) = new void ()(void *);

You could use a std::vector : 你可以使用std::vector

#include <vector>

typedef void (*FunPointer)(void *);
std::vector<FunPointer> pointers;

If you really want to use a static array, it would be better to do it using the FunPointer i defined in the snippet above: 如果你真的想使用静态数组,最好使用上面代码片段中定义的FunPointer

FunPointer testArray[5];
testArray[0] = some_fun_pointer;

Though i would still go for the vector solution, taking into account that you don't know the size of the array during compilation time and that you are using C++ and not C. 虽然我仍然会选择矢量解决方案,但考虑到你在编译期间不知道数组的大小,并且你使用的是C ++而不是C.

With typedef , the new expression is trivial: 使用typedef ,新表达式是微不足道的:

typedef void(*F)(void*);

int main () {
  F *testArray = new F[5];
  if(testArray[0]) testArray[0](0);
}

Without typedef , it is somewhat more difficult: 没有typedef ,它有点困难:

void x(void*) {}
int main () {
  void (*(*testArray))(void*) = new (void(*[5])(void*));
  testArray[3] = x;

  if(testArray[3]) testArray[3](0);
}
for(i=0;i<length;i++)
A[i]=new node

or 要么

#include <vector>

std::vector<someObj*> x;
x.resize(someSize);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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