c++学习-基础-指向函数的指针

/*
	Date: 05/03/21 17:44
	Description: 指向函数的指针
	用typedef简化函数指针的定义
	指向函数的指针的初始化和赋值
	通过指针调用函数
	函数指针形参
	返回指向函数的指针
	指向重载函数的指针 
*/
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;

typedef bool (*cmpFcn)(const string &,const string &);

typedef int (*PF)(int *,int);

bool lengthCompare(const string &s1,const string &s2)
{
	return s1.size()  == s2.size();
} 

string::size_type sumLength(const string &s1,const string &s2)
{
	return s1.size()+s2.size();
}

bool cstringCompare(char *s1,char *s2)
{
	return strlen(s1) == strlen(s2);
}

void useBigger(const string &s1,
			   const string &s2,
			   bool (*pf)(const string &,const string &)) 
{
	cout<<pf(s1,s2)<<endl;
}

int demo(int *p,int a)
{
	return 12;
}
//	ff是一个函数,有一个形参x,返回结果是一个函数指针int(*)(int *,int) 
//int (*ff(int x))(int *,int)
PF ff(int x)
{
	cout<<x<<endl;
	return demo;
} 

void ff(vector<double> vec)
{
	cout<<"ff(vector<double> vec)"<<endl;
}

void ff(unsigned int x)
{
	cout<<"ff(unsigned int x)"<<endl;
}

int main()
{
//	void (*pf5)(int)  = &ff;	[Error] no matches converting function 'ff' to type 'void (*)(int)'
	void (*pf8)(unsigned int) = &ff;
//	double (*pf6)(vector<double>) = &ff;	[Error] no matches converting function 'ff' to type 'double (*)(class std::vector<double>)'
	void (*pf7)(vector<double>) = &ff;//可行 
	int a = 5;
	int *pa;
	cmpFcn pf4 = lengthCompare;
	
	useBigger("hi","function",lengthCompare);//函数的名称就是指向函数的指针 
	
	cout<<ff(2)(&a,a)<<endl;
	
	//pf是一个指针,指向函数的指针:函数的类型 
	//pf是一个局部变量 
//	bool (*pf)(const string &,const string &);
//	bool (*pf2)(const string &,const string &);
//	bool (*pf3)(const string &,const string &);
	cmpFcn pf;
	cmpFcn pf2;
	cmpFcn pf3;
	
	pf2 = lengthCompare;
//	pf3 = sumLength;		//下面这两种都是不可以的,指针与函数类型不匹配 
//	pf3 = cstringCompare;
	
//	pf = &lengthCompare;
	pf = lengthCompare;
	pa = &a;
	
	cout<<lengthCompare("hello","pointer")<<endl;
	cout<<(*pf)("hello","pointer")<<endl;
	cout<<(*pf2)("hello","point")<<endl;
	cout<<*pa<<endl;
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值