tags:
- Cpp
Function Pointers in C++ (Examples)
#include <iostream>
int add(int a, int b){
return a + b;
}
int multiply(int a, int b){
return a * b;
}
int main(){
auto (*fp)(int, int);
bool sel = 1;
if(sel == 0){
fp = add;
std::cout << fp(1, 2) << std::endl;
}else{
fp = multiply;
std::cout << fp(1, 2) << std::endl;
}
return 0;
}
#include <iostream>
// 定义回调函数类型
typedef void (*Callback)(int);
void process(int value, Callback cb) {
std::cout << "Processing value: " << value << std::endl;
cb(value); // 调用回调函数
}
void myCallback(int result) {
std::cout << "Callback function called with result: " << result << std::endl;
}
int main() {
// 使用回调函数
process(42, myCallback);
return 0;
}
std::function
std::function<int(int, int)> op;