C++primer学习:重载运算(2)

关系重载运算符

bool operator!=(const StrVec& lhs, const StrVec& rhs)
{
    return !(lhs == rhs);
}
bool operator==(const StrVec& lhs, const StrVec& rhs)
{
    return(lhs.size() == rhs.size() && equal(lhs.elements, lhs.first_free, rhs.elements));
}
bool operator<(const StrVec& lhs, const StrVec& rhs)
{
    return(lexicographical_compare(lhs.begin(),lhs.end(),rhs.begin(),rhs.end()));
}
bool operator>(const StrVec& lhs, const StrVec& rhs)
{
    return rhs<lhs;
}
bool operator<=(const StrVec& lhs, const StrVec& rhs)
{
    return !(lhs>rhs);
}
bool operator>=(const StrVec& lhs, const StrVec& rhs)
{
    return !(lhs<rhs);
}

下标运算,定义const与非const版本

const string&  operator[](size_t n)const{ return elements[n]; }
    string& operator[](size_t n){ return elements[n]; }

为StrBlobPtr添加递增和递减运算,注意检查边界.

StrBlobPtr& operator++();//前置递增
    StrBlobPtr& operator--();
    StrBlobPtr operator++(int){ auto ret = *this;  ++*this; return ret; }
    StrBlobPtr operator--(int){ auto ret = *this;  --*this; return ret; }
    StrBlobPtr& StrBlobPtr:: operator++()
{
    check(curr, "increment past the end of StrBlobPtr");
    ++curr;
    return *this;
}
StrBlobPtr& StrBlobPtr:: operator--()
{
    --curr;
    check(curr, "increment past the end of StrBlobPtr");
    return *this;
}

===========================================

为StrBlobPtr添加加法运算,实现指针应该有的算术运算.

friend StrBlobPtr operator+(const StrBlobPtr&, int);
    friend StrBlobPtr operator+(int n,const StrBlobPtr& p){ return p + n; };
    friend StrBlobPtr operator-(const StrBlobPtr& p, int n){ return p + (-n); };
    friend int operator-(StrBlobPtr&, const StrBlobPtr&);
StrBlobPtr operator+(const StrBlobPtr& p, int n)
{
     auto ret = p;
     ret.curr += n;
     p.check(ret.curr, "the curr out of range");
     return ret;
}
int operator-(const StrBlobPtr& p1, StrBlobPtr& p2)
 {
     return p1.curr - p2.curr;
 }

你可能感兴趣的:(C++primer学习:重载运算(2))