嗨,我想在C/C++中學習一些函數指針,並試圖在Ubuntu上使用gcc編寫下面的C++代碼。通過引用傳遞函數指針
此代碼應執行編譯
#include <iostream>
#include <iomanip>
//Adds two numbers
int add(int a, int b)
{
return a+b;
}
//Multiplies two numbers
int multiply(int a, int b)
{
return a*b;
}
//Function to set the correct function to be executed.
//All functions here should have the same signature.
void functionsetter(void (*ptr2fun)(int,int) )
{
#ifdef ADD
ptr2fun = add;
#endif
#ifdef MULTIPLY
ptr2fun = multiply
#endif
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 6;
void (*foo)(int,int);
functionsetter(foo);
return 0;
}
期間提供的乘法或或取決於 預處理標誌add函數-DADD或-DMULTIPLY我無法弄清楚如何函數指針foo
傳遞給function-setter
功能通過參考。有人可以幫我解決這個問題。我確信
functionsetter
是錯誤的代碼,請讓我知道如何解決它。
我試圖用g++ -O2 -g -Wall -DADD main.cpp -o main
注意編譯:我想在其他一些代碼來使用這些預處理器標誌和函數指針別處。 請讓我知道這樣的事情是一個好主意/實踐。