仿指针类与仿函数类

一个类,如果它的对象使用时像是指针,或者函数那么这个类就是一个仿指针类与仿函数类。

原理分析:

在使用指针时,我们使用的运算符通常是*, &, ->。

对于函数我们使用的是函数调用运算符,也就是(   )

因此要使得一个类像指针,那么类内重载指针所使用的运算符不就行了。

同理,要使得类像一个函数,那么类内重载函数调用符就行了。

 

仿指针类:

智能指针:

 一个类,却具备指针的功能。

利用了操作符重载。

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;}    
};

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值