pointer-like class

类似于指针的类,该类的功能和指针一致。

智能指针

template<typename T>
class shared_ptr{
  public:
    shared_ptr(T* p):ptr(p) {} 
    T& operator*() const {
        return *ptr;
    }
    T* operator->() const {
        return ptr;
    }
  private:
    T* ptr; 
};

class Widget{
  public:
    void print() {}
  private:
    int m;
};

share_ptr ptr(new Widget);

ptr->print(); //重载的->运算符返回了指针ptr,但是->具有延伸性,可以正确完成该功能。

STL迭代器

STL容器对元素的操作不能直接像普通数组一样方便,需要借助迭代器。而迭代器就是和指针功能类似的类。

template<typename T>
struct __list_node{
  void* prev;
  void* next;
  T data;
};

template<typename T, typename Ref, typename Ptr>
struct __list_iterator{
    typedef __list_iterator<T, Ref, Ptr> self;
    typedef Ptr pointer;
    typedef Ref reference;
    typedef __list_node<T>* link_type;
    link_type node;
    reference operator*() const {
        return (*node).data;
    }
    pointer operator->() const {
        return &(operator*());
    }
    self& operator++() const {
        node = (link_type)node->next;
        return *this;
    }
    self operator++(int) const {
        self tmp = *this;
        ++*this;
        return *tmp;
    }
    self& operator--() const {
        node = (link_type)node->prev;
        return *this;
    }
    self operator--(int) const {
        self tmp = *this;
        --*this;
        return *tmp;
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top