简体   繁体   English

从函数数组中调用C ++函数

[英]C++ calling functions from an array of functions

Sorry I'm totally new to C++ just started this semester. 抱歉,我是本学期刚开始使用C ++的人。 I have a question though. 但我有个问题。 I know javascript some what well and I love how loose it is as a programming language. 我知道javascript有什么用,我喜欢它作为一种编程语言是多么的宽松。 (It's both a good and a bad thing.) But there is one thing you can do in javascript that I'm not sure if you can do in c++. (这既是一件好事也是一件坏事。)但是,您不确定在javascript中可以做一件事,如果您能在c ++中完成,我不确定。

I want to call some functions from an array of functions here is a link of that done in javascript. 我想从函数数组中调用某些函数,这是在javascript中完成的链接。 Javascript Array of Functions . Javascript函数数组 My idea is to write a for loop that will go through functions in the order I want. 我的想法是编写一个for循环,该循环将按我想要的顺序遍历函数。 (from first to last.) If there is an alternative to this I will be fine with that. (从头到尾。)如果有其他选择,我会满意的。 I could even name the functions with a number after them like function1 for example if that might help. 我什至可以在函数后加上一个数字来命名它们,例如function1(如果有帮助的话)。 I'm not sure if this is possible, but any help or anything would be awesome thanks. 我不确定这是否可行,但是任何帮助或任何帮助都将非常感谢。

Do you talk about "function pointer"? 您是否在谈论“函数指针”?

void f1() { .. }
void f2() { .. }
void f3() { .. }

typedef void (*pf)();

pf arf[3] = { f1, f2, f3 };

arf[0]();

If you don't want to use the function pointer 如果您不想使用函数指针

struct parent
{
   virtual void f();
}

struct child1 : parent
{
  void f(){};
}

struct child2 : parent
{
  void f(){};
}

struct child3 : parent
{
  void f(){};
}

.
.
.

struct childn : parent
{
  void f(){};
}


parent array = {child1,child2,child3,.....,childn};

array[n].f();

each child classes will contain different implementations of f(), so you can 

create an array of child structs and invoke the methods through the for loop. 

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

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