函数指针和function的联系
1.函数指针
#include<iostream>
using namespace std;
int add(int a, int b)
{
return a + b;
}
int add2(int a, int b)
{
return a + b +100;
}
typedef int(PfunAdd)(int, int);
void main()
{
PfunAdd *padd = add;
int c = padd(100, 200);
cout << c << endl;
//直接定义
int(*ptest)(int, int) = add2;
int d = ptest(12,18);
cout << d << endl;
system("pause");
}
结果:
函数指针真正的作用在于函数指针做函数参数:
#include<iostream>
using namespace std;
int add(int a, int b)
{
return a + b;
}
int add2(int a, int b)
{
return a + b +100;
}
typedef int(PfunAdd)(int, int);
//函数指针做函数参数
int doSomeExternal(int(*p)(int a, int b), int t)
{
return p(100, 200) + t;
}
void main()
{
int c = doSomeExternal(add,520);
cout << "c:" << c << endl;
system("pause");
}
结果:
函数指针做函数参数利用价值非常高,可以让后来人写的接口被前人调用,这个在以后的开发经验中自己去体会。
2.function
其实function的功能和函数指针很相似,不过它使用更方便。
#include<iostream>
#include<functional>
#include<string>
using namespace std;
int add(int a, int b)
{
return a + b;
}
int add2(int a, int b)
{
return a + b +100;
}
typedef int(PfunAdd)(int, int);
//函数指针做函数参数
int doSomeExternal(int(*p)(int a, int b), int t)
{
return p(100, 200) + t;
}
void showmsg(string temp)
{
cout << temp << endl;
}
void DoExternal(function<void(string)> p)
{
cout << "我做了一些额外的事情\n";
p("hello world!");
}
void main()
{
function<int(int, int)> pF = add;
int c = pF(101,102);
cout << "c:" << c << endl;
function<void(string)> pShow = showmsg;
pShow("hello world!");
//函数对象做函数参数
DoExternal(showmsg);
system("pause");
}
结果:
后面会在所讲内容中拓展function的功能。