C++:指针对象
C语言中的函数指针
在C语言中,我们见过如下的函数指针:
int add(int a, int b) {return a + b;
}int main() {int a, b;int (*p)(int, int) = add;scanf("%d%d", &a, &b);p(a, b);return 0;
}
为了适应C++中面向对象的特性,出现了一个新的对象叫做函数指针对象。
C++中的函数指针对象
C++中的函数对象
在C++中有一类对象本质上是一个对象,但是表现的像个函数:
class Func_add {
public:int operator+()(int a, int b) {return a + b;}
};int main() {Func_add add; // 需要先定义一个函数对象int a , int b;cin >> a >> b;cout << "a + b = " << add(a, b) << endl;return 0;
}
既然有函数对象,可以猜到C语言中的函数指针肯定不能不能指向C++中的函数对象,因此诞生出了函数指针对象,既能够满足原生C语言中的函数指针的要求,也能满足C++中函数对象的要求:
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <ctype.h>
#include <cmath>
#include <string>
#include <sstream>
#include <functional>#define TEST_BEGINS(x) namespace x {
#define TEST_ENDS(x) } // end of namespace x
using namespace std;int add(int a, int b) {return a + b;
}class func{
public:int operator()(int a, int b) {return a + b;}};int main() {int a, b;func func_add;cin >> a >> b;function<int(int, int)> q;q = add;cout << q(a, b) << endl;q = func_add;cout << q(a, b) << endl;return 0;
}
可以看出函数对象都能执行成功。
函数指针对象的用法
很简单,你可以将他当成一个指针来使用,包括赋值一系列操作。
functional<int(int ,int)> q; // 定义了一个具有两个参数int和一个int返回值的函数指针对象;
functional<float(int, float)> p; // 定义了两个传入参数类型分别是 int 和 float 类型,返回值类型是float类型的函数指针对象
C++_STL中的函数对象
那么C++中有什么函数对象呢?其中最为常用的大概就是greater了,他常常在sort函数的排序中作为第三个参数来使用:
srand(time(0));
vector<int> a;
for (int i = 0; i < 100; ++i) {a.push_back(rand() % 100);
}
sort(a.begin(), a.end(), greater<int>());
事实上,这个对象是被当作一个比较方法来使用的。
greater复现
我们可以尝试写一下greater的代码:
TEST_BEGINS(my)
template <typename T>
class greater {
public:bool operator()(T a, T b) {if (a > b) return true;else return false;}
};
TEST_ENDS(my)
只要是能够使用比较运算符的对象就可以使用该比较方法。