重载运算符函数及其注意事项
1 #include "stdafx.h" 2 #include <string> 3 4 class CMyString 5 { 6 public: 7 CMyString(char* pData = NULL); 8 CMyString(const CMyString& str); 9 ~CMyString(void); 10 11 CMyString& operator = (const CMyString& str); 12 13 void Print(); 14 15 private: 16 char* m_pData; 17 }; 18 19 CMyString::CMyString(char *pData) 20 { 21 if(pData == NULL) 22 { 23 m_pData = new char[1]; 24 m_pData[0] = '\0'; 25 } 26 else 27 { 28 int length = strlen(pData); 29 m_pData = new char[length + 1]; 30 strcpy(m_pData, pData); 31 } 32 } 33 34 CMyString::CMyString(const CMyString &str) 35 { 36 int length = strlen(str.m_pData); 37 m_pData = new char[length + 1]; 38 strcpy(m_pData, str.m_pData); 39 } 40 41 CMyString::~CMyString() 42 { 43 delete[] m_pData; 44 } 45 46 CMyString& CMyString::operator = (const CMyString& str) 47 { 48 if(this == &str) 49 return *this; 50 51 delete []m_pData; 52 m_pData = NULL; 53 54 m_pData = new char[strlen(str.m_pData) + 1]; 55 strcpy(m_pData, str.m_pData); 56 57 return *this; 58 } 59 60 // ====================测试代码==================== 61 void CMyString::Print() 62 { 63 printf("%s", m_pData); 64 } 65 66 void Test1() 67 { 68 printf("Test1 begins:\n"); 69 70 char* text = "Hello world"; 71 72 CMyString str1(text); 73 CMyString str2; 74 str2 = str1; 75 76 printf("The expected result is: %s.\n", text); 77 78 printf("The actual result is: "); 79 str2.Print(); 80 printf(".\n"); 81 } 82 83 // 赋值给自己 84 void Test2() 85 { 86 printf("Test2 begins:\n"); 87 88 char* text = "Hello world"; 89 90 CMyString str1(text); 91 str1 = str1; 92 93 printf("The expected result is: %s.\n", text); 94 95 printf("The actual result is: "); 96 str1.Print(); 97 printf(".\n"); 98 } 99 100 // 连续赋值 101 void Test3() 102 { 103 printf("Test3 begins:\n"); 104 105 char* text = "Hello world"; 106 107 CMyString str1(text); 108 CMyString str2, str3; 109 str3 = str2 = str1; 110 111 printf("The expected result is: %s.\n", text); 112 113 printf("The actual result is: "); 114 str2.Print(); 115 printf(".\n"); 116 117 printf("The expected result is: %s.\n", text); 118 119 printf("The actual result is: "); 120 str3.Print(); 121 printf(".\n"); 122 } 123 124 int _tmain(int argc, _TCHAR* argv[]) 125 { 126 Test1(); 127 Test2(); 128 Test3(); 129 130 return 0; 131 }
剑指offer里面提到,如果让写一个重载运算符函数需要注意的4个事项
1:返回值一定要是引用,也就是自身*this,这样才能保证连续赋值
2::形参要是引用不能是实例,否则会自身调用复制构造函数,造成浪费,减慢效率,同时为了不修改,应该const 修饰
3:在分配内存之前要释放以前的内存
4:最初一定要判断*this和传入的是否是同一个,如果是同一个,那么直接返回,否则,会delete全部删除