[英]passing an array of functions by reference C++
There are multiple functions in a file (let's say file1.h).一个文件中有多个函数(比如说file1.h)。 These functions are similar by their definition and return value.
这些函数的定义和返回值相似。 The file itself, it is not allowed to change it.
文件本身,不允许更改。 I wanna simplify them like this:
我想像这样简化它们:
file1.h文件1.h
int func1 (void)
{
return 11;
}
int func2(void)
{
return 12;
}
int func3(void)
{
return 13;
}
In my source file, which I am allowed to change, I would like to create an array of functions then pass this array by reference to another function, the code here is also simplified:在我允许更改的源文件中,我想创建一个函数数组,然后通过引用另一个 function 来传递这个数组,这里的代码也被简化了:
source_file.cpp源文件.cpp
static int func_main(const int idx, int* arr_of_func)
{
int ret = 0;
switch (idx)
{
case 1:
ret = arr_of_func[0];
break;
case 2:
ret = arr_of_func[1];
break;
case 3:
ret = arr_of_func[0];
break;
default:
ret = -1;
break;
}
return ret;
}
int main()
{
std::cout << "Hello World!\n";
int x = 0;
cin >> x;
int (*arr[3])(void) = {func1, func2, func3};
cout << func_main(x, *arr);
system("pause");
}
By invoking the function func_main(x, *arr) I don't know how to pass the array (the second argument).通过调用 function func_main(x, *arr) 我不知道如何传递数组(第二个参数)。 I need your help please.
我需要你的帮助。 Thanks.
谢谢。
Correct func_main
parameter int* arr_of_func
to array of function pointers int (*arr_of_func[3])()
. func_main
参数int* arr_of_func
更正为 function 指针int (*arr_of_func[3])()
的数组。 Arrays are passed by reference by default. Arrays 默认通过引用传递。
#include <string>
#include <functional>
#include <iostream>
int func1 (void)
{
return 11;
}
int func2(void)
{
return 12;
}
int func3(void)
{
return 13;
}
static int func_main(const int idx, int (*arr_of_func[3])())
{
int ret = 0;
switch (idx)
{
case 1:
ret = arr_of_func[0]();
break;
case 2:
ret = arr_of_func[1]();
break;
case 3:
ret = arr_of_func[2]();
break;
default:
ret = -1;
break;
}
return ret;
}
int main()
{
std::cout << "Hello World!\n";
int x = 0;
std::cin >> x;
int (*arr[3])(void) = {func1, func2, func3};
std::cout << func_main(x, arr);
system("pause");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.