1 #include<iostream> 2 #include<string> 3 using namespace std; 4 5 class MyString{ 6 private: 7 char* cp; 8 public: 9 MyString(char*); 10 ~MyString(); 11 MyString(MyString&ms); 12 MyString& operator +(MyString&); 13 MyString&operator=(MyString&); 14 MyString&operator+=(MyString&); 15 char operator[](int i); 16 char* getP(); 17 18 }; 19 MyString::MyString(char*cp=NULL):cp(cp){ 20 } 21 MyString::~MyString(){} 22 MyString::MyString(MyString&ms){//深复制 23 int len = strlen(ms.cp);//先确定原来字符串长度 24 char*tempcp = new char[len+1];//开辟足够的空间 25 strcpy(tempcp,ms.cp);//复制相同的内容 26 cp = tempcp;//初始化对象的指针 27 } 28 29 MyString& MyString:: operator +(MyString&ms){ 30 int len = strlen(cp) + strlen(ms.cp); 31 char *tempcp = new char[len+1]; 32 strcpy(tempcp,cp); 33 strcat(tempcp,ms.cp); 34 35 return *(new MyString(tempcp));//不改变两边对象的内容,返回一个新的对象 36 } 37 MyString&MyString::operator=(MyString&ms){ 38 if (cp == NULL || strlen(cp) < strlen(ms.cp)){ 39 if (cp){ 40 delete[] cp;//释放原来的小空间 41 } 42 cp = new char[(strlen(ms.cp) + 1)];//开辟足够的空间 43 } 44 cp=strcpy(cp, ms.cp);//复制内容 45 return *this; 46 } 47 MyString& MyString::operator+=(MyString&ms){ 48 49 char*tempcp = cp;//暂存cp,因为要重新开辟空间//如果直接使strcat空间不够会出错 50 cp = new char[strlen(cp)+strlen(ms.cp)+1]; 51 strcpy(cp,tempcp); 52 strcat(cp,ms.cp); 53 54 return *this; 55 } 56 char MyString::operator[](int i){ 57 return cp[i]; 58 } 59 char*MyString::getP(){//用于主函数中查看对象内容 60 return cp; 61 } 62 int main(){ 63 MyString ms1("hello"),ms2("world"); 64 cout << "+result:" << (ms1 + ms2).getP() << endl; 65 ms1 += ms2; 66 cout << "+=result:" << ms1.getP() << endl; 67 ms1 = ms2; 68 cout << "=result:" << ms1.getP() << endl; 69 cout << "[]result:" << ms1[0] << endl; 70 71 }