嗨,我想在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
注意编译:我想在其他一些代码来使用这些预处理器标志和函数指针别处。 请让我知道这样的事情是一个好主意/实践。