C++详解(2) 指向函数的指针

  • 函数指针的基本使用
// 省略头文件

bool compare(const int &i1, const int &i2)
{
        return i1 == i2;
}

int main()
{
        bool (*pf)(const int &, const int &);
        // pf 是一个指针,指向函数的指针
        pf = &compare;  // 这里可以去掉取址符&
        pf = compare;  // 同上
        //为什么可以直接使用函数的名称?
        //在c/c++中函数的名称就是指向该函数地址的指针


        cout << compare(1, 2) << endl;
        cout << (*pf)(1, 1) << endl; // 这里可以去掉指针符* 原因同上
        cout << pf(1,2) << endl;  // 同上

        return 0;
}
  • 使用 typedef 来简化函数指针的使用
// 省略头文件

// 可以使用 typedef 来简化函数指针的使用
typedef bool (*cmpFcn)(const int &, const int &);

bool compare(const int &i1, const int &i2)
{
	return i1 == i2;
}

int main()
{
	cmpFcn pf;  // 函数指针没有初始化
	cmpFcn pf2 = 0; // 函数指针等于0 没有指向任何一个函数
	
	pf = compare;
	pf2 = compare;
	
	cout << pf(1, 1) << endl;
	cout << pf2(1, 2) << endl;
	return 0;
}
  • 函数指针类型要匹配
// 省略头文件
typedef bool (*cmpFcn)(const int &, const int &);  // 简化函数指针使用

// 定义add函数,注意这里的函数类型是int,形参是const int
int add(const int &i1, const int &i2)  
{
	return i1 + i2;
}

// 定义compare函数,注意这里的函数类型是bool,形参是const char
bool compare(const char &c1, const char &c2)
{
	return c1 == c2;
}

int main()
{
	cmpFcn pf;
	cmpFcn pf2;
	
	pf = add; // 报错error:指针函数返回类型不一样
	pf = compare;  // 报错error:形参不一样
	
	/*
	总结:如果指针函数的返回类型和形参和原函数不匹配就会报错
	*/
	return 0;
}
  • 函数的指针可以做函数的形参
// 省略头文件
typedef bool (*cmpFcn)(const int &, const int &);

bool compare(const int &i1, const int &i2)
{
	return i1 == i2;
}

void useCompare(const int &i1, const int &i2,
	bool (*pf)(const int &, const int &)
	)
{
	cout << pf(i1, i2) << endl;
}

int main()
{
	cmpFcn pf = compare;
	
	useCompare(1, 1, pf);
	useCompare(1, 2, compare);  // 两种写法都可以,因为函数的名称就是指向该函数地址的指针
	
	return 0;
}
  • 函数的指针可以做函数的返回结果
// 省略头文件
int demo(int a) {return 666;}

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

int main()
{
	int a = 1;
	cout << ff(2)(a) << endl;

	return 0;
}
  • 指向重载函数的指针
// 省略头文件
// 记得引入vector头文件

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

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

int main()
{
	//指向重载函数的函数指针必须要与一个重载函数精确匹配
	void (*pf)(int) = &ff; // error 没有精确匹配
	void (*pf2)(unsigned) = &ff; // 精确匹配 第二个函数

	double (*pf3)(vector<double>) = &ff;  // error 没有精确匹配
	void (*pf4)(vector<double>) = &ff; // 精确匹配 第一个函数
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值