C++primer学习:重载运算(2)
2015-10-26 16:24
429 查看
关系重载运算符
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 ; } string& operator[](size_t n){ return elements ; }
为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++:概述
- 第7周项目2 建立链队算法库
- %p的用法
- DCMTK354之VC++ 2008 MFC应用程序配置完整过程
- c/c++ 学习笔记
- 类String 的构造函数、析构函数和赋值函数
- 技术小白的C语言之路
- C++设计模式之原型模式(改编自C++设计模式)
- VC++中StretchBlt图像失真问题的解决办法
- C/C++面试(5)——sizeof字节计算
- 读《C专家编程》笔记-第三章 分析C语言的声明
- C语言:编写一个程序统计输入字符串中,各个数字、空白字符、以及其他所有字符出现的次数。
- 【详解】C语言:编写一个函数itob(int n,char s[], int b),将整数n转换为以b进制的数。保存到s中。
- c++中try_catch的使用,二维数组动态创建
- C语言--把一个字符串的内容逆序
- C++设计模式之建造者模式(改编自C++设计模式)
- 几种常见排序算法
- C语言--模拟库函数strcpy,strcat,strcmp
- C++内存管理
- [标准C/C++基础]用指针指向string类的对象