一个类,如果它的对象使用时像是指针,或者函数那么这个类就是一个仿指针类与仿函数类。
原理分析:
在使用指针时,我们使用的运算符通常是*, &, ->。
对于函数我们使用的是函数调用运算符,也就是( )
因此要使得一个类像指针,那么类内重载指针所使用的运算符不就行了。
同理,要使得类像一个函数,那么类内重载函数调用符就行了。
仿指针类:
智能指针:
一个类,却具备指针的功能。
利用了操作符重载。
T& operator*() const{ return *px; }
T* operator->() const{ return px; }
注意T* operator->() const{ return px; }
sp->method() 原本->运算符 作用后会 返回px,那么结果应该是pxMethod(), 但是箭头运算符有个特性,运算作用之后会继续作用下去。
迭代器:
&( operator*() ) 首先对item调用operator*运算,也就是对item解引用,因此 &( operator*() ) 返回的就是&(*item)
仿函数类 :
发现了函数的奥秘了吗?我们来看一下count_if函数STL的源代码:
template <class InputIterator, class Predicate>
ptrdiff_t count_if ( InputIterator first, InputIterator last, Predicate pred )
{
ptrdiff_t ret=0;
while (first != last)
if (pred(*first++)) ++ret;
return ret;
}
个人理解: 就是一个类,类中有一个重载 ( )运算,函数调用时就是使用( )函数调用操作符,能使用( )运算符,形式上就像函数。
https://www.cnblogs.com/pjl1119/p/9681468.html
https://blog.csdn.net/m0_38033475/article/details/79561369
仿函数所使用的奇特base classes
有继承一些 base classes
template<class T>
struct identity: public unary_function<T, T>{
const T&
operator()(const T&x) const {return x;}
};
template<class Pair>
struct select1st: public unary_function<Pair, typename Pair::first_type>{
const typename Pair::first_type&
operator()(const Pair& x) const
{return x.first;}
};
template<class T>
struct plus:public binary_function<T, T, T>{
T operator()(const T& x, const T& y) const{ return x+y;}
};