函数指针

PS:刚开始我还不知道函数指针有什么用,因为一个函数当中,弄个指针岂不是很麻烦,调用的时候直接找到函数就行了,在弄个指针指向它岂不是多此一举,但是,这可能是一种封装的机制,把函数封装好,看不到局部函数,可能是一种保护机制吧。。或者在主函数内部直接定义指针,更一目了然。比如qsort啥的,排序的算法已经写好了,但在比较的时候,需要知道哪个大哪个小,这个规则可以由外面的程序来定。小弟初学C++,还有很多不懂的地方,望指教。。

 

#include<iostream>
#include<cstring>
using namespace std;

bool lengthCompare(const string &a,const string &b)
{
	cout<<"1"<<endl;
	return a.size()>b.size();
}

/***************************分割线************************************/ 
void useBigger(const string &a,const string &b,bool (*pf)(const string &c,const string &d))
{
	cout<<"11";
	pf(a,b);
} 


int main()
{
	string a="Yanxueke is a pig";
	string b="Zhanghan";
	//pf=lengthCompare; == pf=&lengthCompare; //pf指向lengthCompare的函数 and &地址符是可选的 
	bool (*pf)(const string &a,const string &b);
	pf=lengthCompare;
	
	useBigger(a,b,pf);
	return 0;
}

 

做了一个题目说用vector保存函数指针,顺便也贴上来吧。

#include<iostream>
#include<cstring>
#include<vector> 
using namespace std;

/*函数名指向该函数的代码在内存中的首地址*/


bool lengthCompare(const string &a,const string &b)
{
	cout<<"1"<<endl;
	return a.size()>b.size();
}

/***************************分割线************************************/ 
void useBigger(const string &a,const string &b,bool (*pf)(const string &c,const string &d))
{
	cout<<"11";
	pf(a,b);
} 

/*typeded的功能是定义一个新的类型*/ 
typedef bool (*pf)(const string &a,const string &b); //声明一个函数指针,必须要定义别名才能放在vector容器中使用 

bool fun_1(const string &a,const string &b)
{
	cout<<"you are my love";
	return false;
}

bool fun_2(const string &a,const string &b)
{
	cout<<"you are my best love";
	return true;
}


int main()
{
	string a="Yanxueke";
	string b="Zhanghan";
	//pf=lengthCompare; == pf=&lengthCompare; //pf指向lengthCompare的函数 and &地址符是可选的 
	//pf=lengthCompare;
	
	vector<pf> v_pf;
	v_pf.push_back(fun_1);
	v_pf[0]("Hello","Hi");
	//useBigger(a,b,pf);
	return 0;
}

 

这次发帖有点仓促,还没来得及准备,下次按一个章节系统整理好之后再发。。

posted on 2014-05-25 01:13  PIMoving  阅读(246)  评论(0)    收藏  举报

导航