gpt4 book ai didi

c++ - C++ 中作为参数的不同类型的函数

转载 作者:太空宇宙 更新时间:2023-11-04 01:37:42 24 4
gpt4 key购买 nike

我正在编写一个程序,我需要针对不同的情况使用不同的函数,并且我需要广泛地使用这些函数。所以,我认为最好的方法是将函数作为参数传递。两者都是双重功能。但是,每个函数所需的参数数量是不同的。我该怎么做?我在下面给出了程序的基本场景。

if (A > B){
func(double x, double y, double func_A(double a1, double a2));
}else{
func(double x, double y, double func_B(double b1, double b2, double b3));
}

最佳答案

您可以重载函数 func 以将不同的回调作为参数:

double func_A(double a1, double a2)
{
return 0;
}
double func_B(double a1, double a2, double a3)
{
return 0;
}

typedef double (*FUNCA)(double,double);
typedef double (*FUNCB)(double,double,double);

void func(double x, double y, FUNCA)
{
}
void func(double x, double y, FUNCB)
{
}

int main()
{
func(0,0,func_A); //calls first overload
func(0,0,func_B); //calls second overload
}

关于c++ - C++ 中作为参数的不同类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11555934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com