在前面文章中使用过几次String类的例子,现在多重载几个运算符,更加完善一下,并且重载流类运算符。
[]运算符重载
+运算符重载
+=运算符重载
<<运算符重载
>>运算符重载
1 | #ifndef _STRING_H_ #define _STRING_H_ #include <iostream> using namespace std; class String private: #endif |
1 | #pragma warning(disable: 4996) #include "String.h" #include <string.h> //#include <iostream> //using namespace std; String::String( const char *str) { str_ = AllocAndCpy(str); } String::String( String &String:: String &String:: String &String::Assign( bool String:: char &String:: const String::~String() char *String::AllocAndCpy( void String::Display() String String &String:: str_ = newstr; ostream & istream & |
1 | #include "String.h" #include <iostream> using namespace std; int main( s1[ String s3 = String s5 = s3 + s4; String s6 = s3 += s4; cout << s3 << endl; String s7; |
需要注意的是,不能将String类的构造函数声明为explicit,否则 String s3 = "xxx"; 编译出错;operator[] 的non const 版本调用了const 版本的实现,其中使用了static_cast和 const_cast 两种类型转换操作符,可以参考这里;operator+ 调用了operator+= 的实现;只能将流类运算符重载为友元函数,因为第一个参数是流类引用,不是String 类。
原文链接: https://www.cnblogs.com/jiangu66/p/3184705.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/95414
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!