gpt4 book ai didi

c - 为什么函数指针有用?

转载 作者:行者123 更新时间:2023-11-30 18:18:02 25 4
gpt4 key购买 nike

所以,我正在查看函数指针,在我看到的示例中,特别是在这个答案 here 中。它们看起来相当多余。

例如,如果我有以下代码:

int addInt(int n, int m) {
return n+m;
}
int (*functionPtr)(int,int);
functionPtr = &addInt;
int sum = (*functionPtr)(2, 3); // sum == 5

看来创建函数指针没有任何目的,直接这样做不是更容易吗?

int sum = addInt(2, 3); // sum == 5

如果是这样,那么您为什么需要使用它们,它们的用途是什么? (以及为什么需要将函数指针传递给其他函数)

最佳答案

简单的指针示例似乎同样毫无用处。当你开始做更复杂的事情时,它会有所帮助。例如:

// Elsewhere in the code, there's a sum_without_safety function that blindly
// adds the two numbers, and a sum_with_safety function that validates the
// numbers before adding them.

int (*sum_function)(int, int);
if(needs_safety) {
sum_function = sum_with_safety;
}
else {
sum_function = sum_without_safety;
}
int sum = sum_function(2, 3);

或者:

// This is an array of functions. We'll choose which one to call based on 
// the value of index.
int (*sum_functions)(int, int)[] = { ...a bunch of different sum functions... };
int (*sum_function)(int, int) = sum_functions[index];
int sum = sum_function(2, 3);

或者:

// This is a poor man's object system. Each number struct carries a table of 
// function pointers for various operations; you can look up the appropriate
// function and call it, allowing you to sum a number without worrying about
// exactly how that number is stored in memory.

struct number {
struct {
int (*sum)(struct number *, int);
int (*product)(struct number *, int);
...
} * methods;
void * data;
};

struct number * num = get_number();
int sum = num->methods->sum(number, 3);

最后一个示例基本上是 C++ 如何执行虚拟成员函数的。将方法结构替换为哈希表,您就拥有了 Objective-C 的方法分派(dispatch)。与变量指针一样,函数指针可以让您以有值(value)的方式抽象事物,从而使代码更加紧凑和灵活。然而,从最简单的例子来看,这种力量并不明显。

关于c - 为什么函数指针有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19215705/

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