【发布时间】:2020-12-17 12:12:52
【问题描述】:
一个文件中有多个函数(比如file1.h)。这些函数的定义和返回值相似。文件本身,不允许更改。我想像这样简化它们:
file1.h
int func1 (void)
{
return 11;
}
int func2(void)
{
return 12;
}
int func3(void)
{
return 13;
}
在我允许更改的源文件中,我想创建一个函数数组,然后通过引用另一个函数来传递这个数组,这里的代码也被简化了:
source_file.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");
}
通过调用函数 func_main(x, *arr) 我不知道如何传递数组(第二个参数)。我需要你的帮助。谢谢。
【问题讨论】:
-
嗯,
int*当然不是对函数数组的引用。你考虑过改变吗?另外,如果你想将 a 引用传递给数组,那么为什么要在其上使用间接运算符呢? -
是的,你完全正确,函数 (func_main()) 我想创建它,所以我不知道应该如何通过引用或指针传递第二个参数。