原创博文,转载请标明出处--周学伟 http://www.cnblogs.com/zxouxuewei/
一,创建测试程序包
测试代码如下:
/* Date: 2017-5-4 * Description: String operator overload test program * Filename: string_operator.h * Author: Myron Zhou */ #ifndef __STRING_OPERATOR_h_ #define __STRING_OPERATOR_h_ #include <iostream> #include <string.h> using namespace std; class MyString { public: //三个重载的构造函数 MyString(); MyString(const char* str); MyString(const MyString& str); //析构函数 ~MyString(); //重载运算符 MyString& operator = (const MyString& str); char& operator[](int index); //访问下标 friend ostream& operator << (ostream& out, const MyString& str); //重载输出操作符 friend istream& operator >> (istream& in, MyString& str); //重载输入操作符 friend MyString operator + (const MyString& str1, const MyString& str2); //重载加号操作符,注意返回引用不行 friend MyString operator += (MyString& str1, const MyString& str2); //重载+=操作符 friend bool operator == (const MyString& str1, const MyString& str2); //重载相等操作符 friend bool operator != (const MyString& str1, const MyString& str2); //重载不相等操作符 private: char* p; int len; }; #endif
/* Date: 2017-5-4 * Description: String operator overload test program * Filename: string_operator.cpp * Author: Myron Zhou */ #include "string_operator.h" using namespace std; //默认构造函数,初始化为空串 MyString::MyString() { len = 0; p = new char[len + 1]; p[0] = '