C++函数指针和function的联系

函数指针和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的功能。

发布了65 篇原创文章 · 获赞 6 · 访问量 1542

猜你喜欢

转载自blog.csdn.net/FairLikeSnow/article/details/103794518
今日推荐