![](/img/trans.png)
[英]Passing Array of objects Composed of other objects as reference to Functions In C++?
[英]passing an array of functions by reference C++
一個文件中有多個函數(比如說file1.h)。 這些函數的定義和返回值相似。 文件本身,不允許更改。 我想像這樣簡化它們:
文件1.h
int func1 (void)
{
return 11;
}
int func2(void)
{
return 12;
}
int func3(void)
{
return 13;
}
在我允許更改的源文件中,我想創建一個函數數組,然后通過引用另一個 function 來傳遞這個數組,這里的代碼也被簡化了:
源文件.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");
}
通過調用 function func_main(x, *arr) 我不知道如何傳遞數組(第二個參數)。 我需要你的幫助。 謝謝。
func_main
參數int* arr_of_func
更正為 function 指針int (*arr_of_func[3])()
的數組。 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.