[C++] pointer-like classes 和 function-like classes

1. pointer-like class 意思是像指针的类,是指一个类被设计成像指针一样,可以当做指针来使用。下面来介绍两种常见的指针类:智能指针和迭代器。

a. 智能指针

namespace ll {
    template
    class shared_ptr
    {
    public:
        T& operator* () const {
            return *px;    //返回指针所指的对象
        }
        T* operator->() const {
            return px;
        }
        shared_ptr(T* p): px(p) {}
    private:
        T *px;    
    };
}

struct Foo
{
    void method() {
        cout << "method" << endl;
    }
};

ll::shared_ptr sp(new Foo);  // 定义了一个指向Foo类型的智能指针
Foo f(*sp);  // 定义了一个Foo对象,并使用智能指针sp所指向的对象来进行初始化
f.method();  // 通过对象f调成成员函数
sp->method();  // 见下面的解释

  上述代码申明了一个智能指针sp,并通过->操作符来调用成员函数。sp->method();会首先调用操作符函数 operator->() const,得到智能指针内部真实的指针px,然后再通过px调用method函数(px->method())。在这里的疑问是,sp->通过调用操作符函数operator->()已经消耗了一个->符号,px->method()的->是如何来的?C++规定,对于调用->操作符后,->操作符并不消耗,而是会继续作用下去,这样一来,sp->method();便等同于sp->method();

b.迭代器

namespace ll {
    template
    struct __list_node {
        void *prev;
        void *next;
        T data;
    };

    template
    struct __list_iterator {
        typedef __list_iterator self;
        typedef Ptr pointer;
        typedef Ref reference;
        typedef __list_node* link_type;
        link_type node;

        reference operator*() const {
            return (*node).data;
        }
        pointer operator->() const {
            return &(operator*());
        }
        self& operator++() {
            node = (link_type)((*node).next);
            return *this;
        }
        self& operator--() {
            node = (link_type)((*node).prev);
            return *this;
        }  
    };
}



//上述代码的使用代码
struct Foo
{
    void method() {
        cout << "method" << endl;
    }
};

ll::__list_iterator iter;
*iter;  // 获得一个Foo对象
iter->method();  // 意思是调用Foo::method(),相当于(*iter).method(),也相当于(&(*iter))->method()

  首先,我们申明一个_list_iterator迭代器iter,通过*操作符可以得到一个Foo对象,iter->method();则调用Foo::method(),解释如下:

  iter->method();会首先调用operator->() const函数,由于operator->() const里还会调用operator*()先取得data,然后再取地址,所有operator->() const会返回data的地址,在上例中即是Foo对象的地址,这样,通过->操作符便可以调用到Foo::method();

注:->符号的含义, 成员提取,例如 A->B, A是指向类、结构、联合的指针,A->B是指提取A中的成员B。

 

2. function-like classes 仿函数的类

  仿函数的类的特点是重载了操作符operator(),如下面的例子:


template 
struct pair
{
  T1 first;
  T2 second; //first和second类型不需要一样
  pair() : first(T1()), second(T2()) {}
  pair(const T1& a, const T2& b)
  : first(T1()), second(T2())
......
};



template
struct identity : public unary_function
{
  const T&
  operator() (const T& x) const { return x; }
};
 
template
struct select1st : public unary_function
{
  const typename Pair::first_type&
  operator() (const Pair& x) const { return x.first; }
};
 
template
struct select2nd : public unary_function
{
  const typename Pair::second_type&
  operator() (const Pair& x) const { return x.second; }
};

 

参考博客:

https://blog.csdn.net/lihao21/article/details/50668271

https://blog.csdn.net/SUSU0203/article/details/80478029

你可能感兴趣的:(C++)