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!