面试宝典-面试题1
一、题意:对赋值操作符进行重定义,使其可以进行类对象的赋值
二、代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstring> 2 #include<cstdio> 3 #include<iostream> 4 using namespace std; 5 6 class CMyString 7 { 8 public: 9 CMyString(char* pData = nullptr); 10 CMyString(const CMyString& str); 11 ~CMyString(void); 12 13 CMyString& operator = (const CMyString& str); 14 15 void Print(); 16 17 private: 18 char* m_pData; 19 }; 20 21 CMyString::CMyString(char *pData) 22 { 23 if(pData == nullptr) 24 { 25 m_pData = new char[1]; 26 m_pData[0] = '\0'; 27 } 28 else 29 { 30 int length = strlen(pData); 31 m_pData = new char[length + 1]; 32 strcpy(m_pData, pData); 33 } 34 } 35 36 CMyString::CMyString(const CMyString &str) 37 { 38 int length = strlen(str.m_pData); 39 m_pData = new char[length + 1]; 40 strcpy(m_pData, str.m_pData); 41 } 42 43 CMyString::~CMyString() 44 { 45 delete[] m_pData; 46 } 47 48 CMyString& CMyString::operator = (const CMyString& str) 49 { 50 if(this == &str) 51 return *this; 52 53 delete []m_pData; 54 m_pData = nullptr; 55 56 m_pData = new char[strlen(str.m_pData) + 1]; 57 strcpy(m_pData, str.m_pData); 58 59 return *this; 60 } 61 62 // ====================测试代码==================== 63 void CMyString::Print() 64 { 65 printf("%s", m_pData); 66 } 67 68 void Test1() 69 { 70 printf("Test1 begins:\n"); 71 72 char* text = "Hello world"; 73 74 CMyString str1(text); 75 CMyString str2; 76 str2 = str1; 77 78 printf("The expected result is: %s.\n", text); 79 80 printf("The actual result is: "); 81 str2.Print(); 82 printf(".\n"); 83 } 84 85 // 赋值给自己 86 void Test2() 87 { 88 printf("Test2 begins:\n"); 89 90 char* text = "Hello world"; 91 92 CMyString str1(text); 93 str1 = str1; 94 95 printf("The expected result is: %s.\n", text); 96 97 printf("The actual result is: "); 98 str1.Print(); 99 printf(".\n"); 100 } 101 102 // 连续赋值 103 void Test3() 104 { 105 printf("Test3 begins:\n"); 106 107 char* text = "Hello world"; 108 109 CMyString str1(text); 110 CMyString str2, str3; 111 str3 = str2 = str1; 112 113 printf("The expected result is: %s.\n", text); 114 115 printf("The actual result is: "); 116 str2.Print(); 117 printf(".\n"); 118 119 printf("The expected result is: %s.\n", text); 120 121 printf("The actual result is: "); 122 str3.Print(); 123 printf(".\n"); 124 } 125 126 int main(int argc, char* argv[]) 127 { 128 Test1(); 129 Test2(); 130 Test3(); 131 132 return 0; 133 }