指向函数的指针

本文深入探讨了C++中函数指针的应用,包括如何定义和使用函数指针,通过实例展示了不同类型函数指针的用法,如指向普通函数、成员函数等,并解释了函数指针在实际编程中的作用。
#include <iostream>
#include <string>
#include <vector>

using namespace std;

typedef bool (*cmpFcn) (const string&, const string&);// typedef简化指针的定义,
bool lengthCompare(const string &s1, const string &s2)
{
	return s1.size() == s2.size();
}
void ff(vector<double> vec)
{
	cout << "ff(vector<double> vec)" << endl;
}
void ff(unsigned int x)
{
	cout << "ff(unsigned int x)" << endl;
}
int demo (int *p, int a)
{
	return 12;
}

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

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

int main ()
{
	bool (*pf)(const string &, const string &); // pf是一个指针,指向函数的指针:函数类型,
	void (*pf7)(vector<double>) = &ff;
	cmpFcn pf4 = lengthCompare;
	useBigger("hi", "function", pf4);  // 函数的名称就是一个指针,
	int a = 5;
	int *pa;
	cout << ff(2)(&a, a) << endl;  // 一个输出是2,另一个输出是12,
	
	//pf 是一个局部变量,
	// bool (*pf2)(const string&, const string&); 
	//bool (*pf3)(const string&, const string&); 
	cmpFcn pf2;
	cmpFcn pf3 = 0;
	pf2 = lengthCompare;
	pf3 = lengthCompare;

	pf = &lengthCompare;
	cout << lengthCompare("hello", "pointer") << endl;  // 输出是0,
	cout << (*pf)("hello", "point") << endl;  // 输出是1,

	return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值