其他分享
首页 > 其他分享> > 运算符重载-mstring迭代器

运算符重载-mstring迭代器

作者:互联网

实现代码:

#pragma once
#ifndef MITERATOR_h
#define MITERATOR_h
//#include"mstring.h"
class Mstring;

class Miterator
{
private:
    Mstring* _p_mstr;
    int _sit;
public:
    Miterator(Mstring* p_mstr, const int sit)
    {
        _p_mstr = p_mstr;
        _sit = sit;
    }

    Miterator(const Miterator& src)
    {
        _p_mstr = src._p_mstr;
        _sit = src._sit;
    }

    Miterator& operator++()//先自加,然后返回解引用this
    {
        ++_sit;
        return *this;
    }

    Miterator operator++(int)//后置不能返回引用   //要进行构造,拷贝构造要加const
    {
        return Miterator(_p_mstr, _sit++);
    }

    Miterator& operator--()
    {
        --_sit;
        return *this;
    }

    Miterator operator--(int)
    {
        return Miterator(_p_mstr, _sit--);
    }

    bool operator==(const Miterator& src)//确定指向同一个str,两个sit要相同
    {
        if (_p_mstr == src._p_mstr && _sit == src._sit)
        {
            return true;
        }
        return false;
    }

    bool operator!=(const Miterator& src)
    {
        if (_p_mstr == src._p_mstr && _sit == src._sit)
        {
            return false;
        }
        return true;
    }

    char& operator*();
    /*
    {
        return (*_p_mstr)[_sit];
    }
    */
};



#endif 

测试代码:

#include<iostream>
#include<string>
//#include"miterator.h"
#include"mstring.h"
using namespace std;

/*
namespace gg
{
    typedef int Int;
}
*/


int main()
{
#if 0
    /*
    ++ -- !=  ==  *
    end();
    begin();
    */
    string s1 = "abcdefg";

    string::iterator it1 = s1.begin();


    for (; it1 != s1.end(); it1++)
    {
        cout << *it1 << endl;
    }
    it1--;

    string::iterator it3 = it1;
    it1--;
    if (it1 == it3)
    {
        cout << "it1 == it3" << endl;
    }
    else
    {
        cout << "it1 != it3" << endl;
    }



    string s2 = "poiutyrr";
    string::iterator it2 = s2.begin();
    cout << s2 << endl;
    cout << *it2 << endl;
    *it2 = 'm';
    cout << *it2 << endl;
    /*
    if (it1 == it2)
    {
        cout << "it1 = it 2" << endl;;
    }
    else
    {
        cout << "it1 != it2" << endl;
    }*/

#endif

    Mstring str1 = "1234567";
    Mstring::miterator its1 = str1.begin();
    for (; its1 != str1.end(); its1++)
    {
        (*its1)++;
        cout << *its1 << endl;
    }
    return 0;
}

 

标签:mstring,return,迭代,Miterator,sit,mstr,运算符,operator,src
来源: https://www.cnblogs.com/xpei-1124/p/14864308.html