c++之函数指针和函数对象

定义:
函数指针:是指向函数的指针变量,在C编译时,每一个函数都有一个入口地址,那么这个指向这个函数的函数指针便指向这个地址。
函数指针的用途是很大的,主要有两个作用:用作调用函数、做函数的参数和作为函数返回值。

函数对象:实质上是一个实现了operator()-括号操作符重载类的对象。
函数对象可附加数据,使程序设计更加灵活。而且能够实现函数的内联(inline)调用,使整个程序实现性能加速。

使用:
函数指针:

#include<iostream>
using namespace std;
int AddFunc(int a, int b)
{
	return a + b;
}
int main()
{
	typedef int(*Add) (int a, int b);
	Add add;
	add = AddFunc;
	add = &AddFunc;//两种方式都可以
	cout << add(3, 2) << endl; // 5
	system("pause");
	return 0;
}
#include<iostream>
using namespace std;
int AddFunc(int a, int b)
{
	return a + b;
}
int main()
{
	int(*Add) (int a, int b);
	Add = AddFunc;
	Add = &AddFunc;//两种方式都可以
	cout << Add(3, 2) << endl; // 5
	system("pause");
	return 0;
}

函数对象:

#include<iostream>
using namespace std;
class Add
{
public:
	int operator()(int a, int b)
	{
		return a + b;
	}
};
int main()
{
	Add add;
	cout << add(3, 2) << endl; // 5

	system("pause");
	return 0;
}

函数对象有点:
可以携带附加数据
现在用compare_nocase的函数指针作为参数,假如突然又有一个地方要求你比较字符串,但此时要求你忽略首字母,从第二个字符串开始比较,那么你应该怎么做?

1.要么你重新写一个compare_nocase2函数,但会造成大量重复代码。
2.要么你弄个int start变量,然后放在compare_nocase的外面,在执行我刚才说的这个需求时候,先改变start=2,执行完以后再把全局变量改回去。

可以看到,都不优雅。或许你想到了把compare_nocase写到一个类里,但这必须要是static method。但函数对象可以解决:

struct mylistSort {
  int start;
  mylistSort(int p) { start = p; }
  bool operator() (string first, string second) const {
    int i=start-1;
    while ( (i<first.length()) && (i<second.length()) ) {
      if (tolower(first[i])<tolower(second[i])) return true;
      ++i;
    }
    if (first.length()<second.length()) return true;
    else return false;
  }
};

这样你从首字符开始比较就可以mylist.sort(mylistSort(1));而当你需要忽略首字符,从第二个字母开始比较的时候就可以mylist.sort(mylistSort(2));

再举个例子:

#include<iostream>
using namespace std;
class Less
{
public:
	Less(int num) :n(num) {}
	bool operator()(int value)
	{
		return value < n;
	}
private:
	int n;
};
int main()
{
	Less isLess(10);//保留了附加数据
	cout << isLess(9) << " " << isLess(12); // 输出 1 0
	system("pause");
	return 0;
}

更复杂一些

#include<iostream>
#include <algorithm>
using namespace std;
class Less
{
public:
	Less(int num) :n(num) {}
	bool operator()(int value)
	{
		return value < n;
	}
private:
	int n;
};
int main()
{
	const int SIZE = 5;
	int array[SIZE] = { 50, 30, 9, 7, 20 };
	// 找到小于数组array中小于10的第一个数的位置 
	int * pa = std::find_if(array, array + SIZE, Less(10)); // pa 指向 9 的位置 
	// 找到小于数组array中小于40的第一个数的位置 
	int * pb = std::find_if(array, array + SIZE, Less(40)); // pb 指向 30 的位置

	cout << *pa << " " << *pb << endl;
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值