本文介绍了C++ 运算符重载的用法,以我们构造的string类为例子,说明重载的用法。
构造我们自己的string类
声明如下
1 | class mystring_ |
在string类里重载了输出运算符<<
,赋值运算符=, 加法运算符+, 取下标运算符[], 又声明了友元类mystringOpr。
1 | class mystringOpr_ |
该类重载了()运算符,这样mystringOpr的实例对象就是可调用对象了,可以当作仿函数使用。
mystring_类的具体实现
我们先实现构造函数和析构函数
1 | mystring_::mystring_(/* args */) : m_str("") |
实现了形参不同的拷贝构造函数,包括const string类型,const char*
类型,const mystring_ &类型,以及默认的无参构造函数。
接下来重载+运算符
1 | mystring_ operator+(const mystring_ &str1, const mystring_ &str2) |
重载=运算符
1 | mystring_ &mystring_::operator=(const mystring_ &mystr) |
重载输出运算符
1 | ostream &operator<<(ostream &os, const mystring_ &mystr1) |
重载取下表运算符[]
1 | char mystring_::operator[](unsigned int index) |
我们写一个函数测试重载效果
1 | void use_mystr_1() |
测试结果如下
1 | use mystring_ construct , param is const char * |
可以看出调用不同的构造函数会打印不同的日志,重载+运算符实现了字符串的拼接,重载赋值实现了拷贝。
通过仿函数mystringOpr_实现排序
我们先实现仿函数,这样就可以对我们mystring_类对象排序了
1 | bool mystringOpr_::operator()(const mystring_ &str1, const mystring_ &str2) |
我们调用sort实现mystring_排序,在原来的基础上补充排序代码
1 | void use_mystr_1() |
上述代码通过sort排序vector里的mystring_对象,并用lambda表达式输出,可以看到输出
1 | use mystring_ construct , param is const char * |
我们通过仿函数和sort实现了mystring_从大到小的排序。
总结
源码链接:https://gitee.com/secondtonone1/cpplearn
视频链接: https://www.bilibili.com/video/BV1zu411e7DW/