gpt4 book ai didi

c - 函数指针在这里如何工作?

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

我在这里问了一个关于函数指针的使用的问题,有人回答给出了经典计算器的例子

float Plus    (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide (float a, float b) { return a/b; }

in some way you select your operation

/* Here there should be an if or a switch/case that selects the right operation */
float (*ptrFunc)(float, float) = Plus;

现在他说“这里应该有一个 if 或一个 switch/case 来选择正确的操作”

并且已经阅读了很多次函数指针可以用来替换 if 或 switch/case 语句但无法理解(即使在这个计算器示例中)函数指针如何替换 if 或 switch/case?

任何人都可以帮助我如何可视化替换 if 或 switch/case 的函数指针。

最佳答案

如果您需要多次调用计算器函数,那么您只需决定调用一次哪个函数,然后根据需要多次调用。

if (something) {
ptrFunc = Plus;
} else {
ptrFunc = Minus;
}

c = ptrFunc(a, b);
z = ptrFunc(x, y);

关于c - 函数指针在这里如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10130041/

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