如何动态创建函数数组?

时间:2012-04-02 19:38:20

标签: c++ function-pointers

如果我想拥有一个指向函数的指针数组并且从一开始就不知道数组的大小,该怎么办?我只是好奇是否有办法做到这一点。使用新的声明或其他东西。看似与

相似的东西
void (* testArray[5])(void *) = new void ()(void *);

3 个答案:

答案 0 :(得分:8)

您可以使用std::vector

#include <vector>

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

如果您真的想使用静态数组,最好使用上面代码段中定义的FunPointer i来实现:

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

虽然我仍然会选择矢量解决方案,但考虑到你在编译期间不知道数组的大小,并且你使用的是C ++而不是C。

答案 1 :(得分:5)

使用typedef,新表达式很简单:

typedef void(*F)(void*);

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

没有typedef,有点困难:

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

  if(testArray[3]) testArray[3](0);
}

答案 2 :(得分:1)

for(i=0;i<length;i++)
A[i]=new node

#include <vector>

std::vector<someObj*> x;
x.resize(someSize);
相关问题