C++程序设计兼谈对象模型(侯捷)——课程笔记(二)

本篇内容为pointer-like classes,直译过来就是像指针的类,就比如说C++里面的智能指针,迭代器等都是这样的东西。本篇只讨论这类class的语法,不涉及智能指针,迭代器等的使用细节。

一、关于智能指针

template <class T>
class shared_ptr
{
public:
    T& operator*() const
    { return *px; }

    T* operator->() const
    { return px; }

    shared_ptr(T* p) : px(p) { }

private:
    T*    px;
    long* pn;
......
};

struct Foo
{
    ...
    void method(void);
};

shared_ptr<Foo> sp(new Foo());

Foo f(*sp);

sp->method(); //相当于执行px->method()

关键的就是两个操作符的重载,operator*()和operator->()。对于*的重载返回的是指针所指对象的引用,返回值应该是引用类型,因为这个对指针解引用这个操作是可以作为左值的。对于->的重载有一个比较tricky的地方,就是比如说上例中的sp->method()相当于执行px->method(),但是sp->按理说返回的只是px,也就是调用sp的操作符重载将会消耗一个->,那为什么对于px还是会有一个->呢?我们可以这样理解:箭头符号比较特别,得到的东西会继续使用箭头符号作用上去,可以理解为语言设计的一个规则。

二、关于迭代器

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

template <class T, class Ref, class 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;
    bool operator==(const self& x) const { return node == x.node; }
    bool operator==(const self& x) const { return node == x.node; }
    reference operator*() const { return (*node).data; }
    pointer operator->() const { return &(operator*()); }
    ...
};

重要的还是两个操作符重载函数

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值