1. 函数指针的基本概念
函数指针是指向函数的指针。它用于存储函数的地址,可以像调用普通函数一样通过函数指针调用函数。
示例代码:
#include <iostream>
using namespace std;
void myFunction(int x) {
cout << "Value: " << x << endl;
}
int main() {
// 声明函数指针
void (*funcPtr)(int);
// 将函数指针指向myFunction
funcPtr = myFunction;
// 通过函数指针调用函数
(*funcPtr)(10); // Output: Value: 10
// 或者可以简写为
funcPtr(10); // Output: Value: 10
return 0;
}
2. 使用函数指针作为参数
函数指针可以作为参数传递给其他函数,这使得回调函数和函数的高级抽象成为可能。
示例代码:
#include <iostream>
using namespace std;
void greetMorning() {
cout << "Good morning!" << endl;
}
void greetEvening() {
cout << "Good evening!" << endl;
}
void greet(void (*greetFunc)()) {
greetFunc();
}
int main() {
greet(greetMorning);
greet(greetEvening);
return 0;
}
3. 函数指针作为返回值
函数指针也可以作为函数的返回值。这允许根据条件返回不同的函数。
示例代码:
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
// 返回类型是指向函数的指针,该函数接收两个int并返回一个int
int (*getOperation(char op))(int, int) {
if (op == '+') {
return add;
} else if (op == '*') {
return multiply;
}
return nullptr;
}
int main() {
auto operation = getOperation('+');
cout << operation(5, 3) << endl; // Output: 8
operation = getOperation('*');
cout << operation(5, 3) << endl; // Output: 15
return 0;
}
4. 函数指针数组
函数指针数组是存储多个函数指针的数组。这在实现函数查表特别有用。
示例代码:
#include <iostream>
using namespace std;
void function1() {
cout << "Function 1" << endl;
}
void function2() {
cout << "Function 2" << endl;
}
void function3() {
cout << "Function 3" << endl;
}
int main() {
// 函数指针数组
void (*functionArray[3])() = {function1, function2, function3};
for (int i = 0; i < 3; i++) {
(*functionArray[i])(); // 或者可以简写为 functionArray[i]();
}
return 0;
}
5. 使用typedef简化函数指针的声明
typedef
关键字可以用来简化函数指针的声明,使其更易于阅读和使用。
示例代码:
#include <iostream>
using namespace std;
typedef void (*GreetFunction)();
void greetMorning() {
cout << "Good morning!" << endl;
}
void greetEvening() {
cout << "Good evening!" << endl;
}
void greet(GreetFunction greetFunc) {
greetFunc();
}
int main() {
GreetFunction morningGreet = greetMorning;
GreetFunction eveningGreet = greetEvening;
greet(morningGreet);
greet(eveningGreet);
return 0;
}