#include <iostream>
#include <cstdlib>
using namespace std;
// 声明函数指针变量
int (*fn)(int) = NULL;
// 定义函数指针类型
typedef int (*Fn)(int);
int cal(int v){
return v;
};
int max(int a, int b){
return a > b ? a : b;
}
// 函数指针做为参数
void proc(int v, Fn f){
cout << f(v) << endl;
};
// 函数指针作为函数返回值
int (* retFP(string fName))(int, int){
// lambda 表达式作为函数指针返回
int (*fp)(int,int) = [](int x, int y){ return x > y ? y : x;};
// 返回一个全局函数
if(fName == "max"){
fp = max;
}
return fp;
}
// 或者下面的方式
typedef int (*RetFP)(int, int);
RetFP retFP(string fName){
int (*fp)(int,int) = [](int x, int y){ return x > y ? y : x;};
if(fName == "max"){
fp = max;
}
return fp;
}
int main()
{
fn = cal;
cout << (*fn)(10) << endl;
cout << fn(10) << endl;
Fn f1 = cal;
cout << (*f1)(20) << endl;
proc(30, cal);
auto myFP = retFP("max");
cout << myFP(3, 6) << endl;
return 0;
}
Start
10
10
20
30
0
Finish
成员函数指针:
struct type
{
int i;
type(): i(3) {}
void f(int v) const
{
// this->i = v; // compile error: this is a pointer to const
const_cast<type*>(this)->i = v; // OK as long as the type object isn't const
}
};
int main()
{
type t; // if this was const type t, then t.f(4) would be undefined behavior
t.f(4);
std::cout << "type::i = " << t.i << '\n'; // type::i = 4
void (type::*pmf)(int) const = &type::f; // pointer to member function
(t.*pmf)(40);
std::cout << "type::i = " << t.i << '\n'; // type::i = 40
}