迭代器

迭代器的編寫Cstring 嵌套類(訪問私有成員) 類似普通指針 遍歷容器

#include<iostream>
#include<string>
using namespace std;

class Cstring
{
public:
    Cstring(char *p=NULL)//構造函數 帶一個參數或不帶參數的構造 
    {
        if (p != NULL)
        {
            mpstr=new char[strlen(p)+1];
            strcpy(mpstr,p);
        }
        else
        {
            mpstr=new char[1];
            *mpstr=0;
        }
    }
    Cstring(const Cstring &src)//因爲會發生淺拷貝 所以需要自己定義拷貝構造函數
    {
        mpstr =new char[strlen(src.mpstr)+1];
        strcpy(mpstr,src.mpstr);

    }
    Cstring & operator=(const Cstring &src)//賦值運算符重載
    {
        if (this == &src) //防止自賦值
        {
            return *this;
        }

        delete []mpstr; //釋放原來空間
        mpstr=NULL;

        mpstr = new char[strlen(src.mpstr) + 1];
        strcpy(mpstr,src.mpstr);
        return *this;
    }
    ~Cstring()//析構
    {
        delete []mpstr;
        mpstr=NULL;
    }
    bool operator >(const Cstring &src)//大於運算符的重載
    {
        return strcmp(mpstr,src.mpstr) > 0 ? true:false;
    }

    bool operator <(const Cstring &src)//小於運算符的重載
    {
        return strcmp(mpstr,src.mpstr) < 0 ? true:false;
    }

    bool operator == (const Cstring &src)//等於運算符的重載
    {
        return strcmp(mpstr,src.mpstr) == 0 ? true:false;
    }

    //求字符串長度大小
    unsigned int size()const{return strlen(mpstr);}

    //[]運算符的重載函數  [] * -> 一般都實現兩種方法 普通方法和常方法

    char & operator[](int i){ return mpstr[i];}

    //這裏char & 之前加const 主要是因爲防止參數被修改 只讀的“hello”字符串常量不能被修改
    const char & operator[](int i)const {return mpstr[i];}


    //返回當前指針
    const char * c_str()const{return mpstr;}
    //解引用重載
    char operator *()
    {
        return *mpstr;
    }
    const char operator *()const
    {
        return *mpstr;
    }
    class Citerator//迭代器
    {
    public:

        Citerator(Cstring *p=NULL,int pos=0):mpiter(p)
        {  
               mindex=mpiter->mpstr+pos;
        }
        void operator++()
        {
            ++mindex;
        }
        char& operator *(){return *mindex;}
        const char& operator *()const {return *mindex;}
        //這裏的不等於是所指的位置不相等,而不是解引用的值不相等
        bool operator !=(const Citerator &src){return mindex != src.mindex ? true:false;}
    private:
        Cstring *mpiter;//類類型指針,指向該對象的指針,指向要操作的對象
        char *mindex;  //用戶使用類型的指針,指向目前所在位置的下標
    };

    Citerator begin(){return Citerator(this,0);}
    Citerator end(){return Citerator(this,strlen(mpstr));}

    typedef Citerator iterator; //類型重定義

private:
    char* mpstr;
    friend ostream& operator<<(ostream &out, const Cstring &src);
};
ostream& operator<<(ostream &out, const Cstring &src)
{
    out << src.mpstr;
    return out;
}


int main()
{
    Cstring str10("helloworld");
    Cstring::iterator it =str10.begin(); //這裏的it是指針
    for ( ; it != str10.end();++it)
    {
        cout<< *it <<" "; // it.operator*()
    }
    cout<<endl;
}

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章