您的位置:首页 > 编程语言 > C语言/C++

【ThinkingInC++】59、关于operator->

2014-09-25 19:18 453 查看
/**
* 书本:【ThinkingInC++】
* 功能:关于operator->
* 时间:2014年9月25日19:22:01
* 作者:cutter_point
*/

#include <iostream>
#include <vector>
#include "../require.h"

using namespace std;

class Obj
{
    static int i, j;
public:
    void f() const {cout<<i++<<endl;}
    void g() const {cout<<j++<<endl;}
};

int Obj::i=47;
int Obj::j=11;

//容器,包含Obj对象的类
class ObjContainer
{
    vector<Obj*> a; //容器里面是关于Obj类的指针
public:
    void add(Obj* obj) {a.push_back(obj);}
    friend class SmartPointer;  //为这个类声明友元类,方便后面访问a
};

class SmartPointer
{
    ObjContainer& oc;
    int index;
public:
    SmartPointer(ObjContainer& objc) : oc(objc) {index=0;}
    //前缀加加
    bool operator++()
    {
        if(index >= oc.a.size()) return false;
        if(oc.a[++index] == 0) return false;
        return true;
    }
    //后缀加加
    bool operator++(int)
    {
        return operator++();
    }

    Obj* operator->() const
    {
        require(oc.a[index] != 0, "Zero value returned by SmartPointer::operator->()");
        return oc.a[index];
    }
};

int main()
{
    const int sz=10;
    Obj o[sz];
    ObjContainer oc;
    for(int i=0 ; i<sz ; ++i)
        oc.add(&o[i]);
    SmartPointer sp(oc);

    do
    {
        sp->f();
        sp->g();
    }while(sp++);

    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: