question1 赋值运算操作符
注意的问题书上讲的很详细了
下面是代码实现,但是VS有一个问题,strcpy安全性较低,虽然可以通脱编译,但是运行会报错,提示用strcpy_s()替代,但是,这里用strcpy()替代也不行,
1 //题目:如下为类型CMyString的声明,请为该类型添加赋值运算符 2 //以下为完整代码和测试用例 3 #pragma warning(disable:4996) 4 #include <iostream> 5 #include <cstring> 6 using namespace std; 7 class CMyString { 8 public: 9 CMyString(char* pData = nullptr); 10 CMyString(const CMyString& str); 11 ~CMyString(void); 12 // operator "=" 13 CMyString& operator =(const CMyString& str); 14 void print();//用来输出测试结果 15 private: 16 char*m_pData; 17 }; 18 19 //the defination of the constructor fun 20 CMyString::CMyString(char* pData) 21 { 22 if (pData == nullptr) 23 m_pData = new char[1]; 24 m_pData[0] = '\0'; 25 } 26 27 CMyString::CMyString(const CMyString& str) 28 { 29 int len = strlen(str.m_pData); 30 m_pData = new char[len + 1]; 31 //m_pData(str.m_pData); 32 strcpy(m_pData, str.m_pData); 33 34 } 35 36 CMyString::~CMyString() 37 { 38 //delete m_pData[]; 39 delete[]m_pData; 40 } 41 42 CMyString& CMyString:: operator =(const CMyString &str) 43 { 44 if (this == &str); 45 return *this; 46 47 delete[]m_pData; 48 m_pData = nullptr; 49 50 m_pData = new char[strlen(str.m_pData) + 1]; 51 strcpy(m_pData, str.m_pData); 52 return *this; 53 54 } 55 56 void CMyString:: print() 57 { 58 cout << m_pData << endl; 59 } 60 //测试用例 61 62 void test1() 63 { 64 char* str = "Hello World!"; 65 CMyString str1(str); 66 CMyString str2; 67 str2 = str1;//call CMystring& operator=(const CMyString& str) 68 cout << " str is : " << str << endl; 69 //cout << "str2 is : " << str2.print() << endl;//没有重载<<运算符,还不能用 70 cout << "after 赋值" <<"str2 is : "<< endl; 71 str2.print(); 72 } 73 74 void test2()//赋值给自己 75 { 76 char* str = "Hello world!"; 77 CMyString str1(str); 78 str1=str1; 79 cout << " str is : " << str << endl; 80 81 cout << "after 赋值" << "str1 is : " << endl; 82 str1.print(); 83 84 } 85 86 void test3()//连续赋值 87 { 88 char* str = "Hello World!"; 89 CMyString str1(str); 90 CMyString str2, str3; 91 str3 = str2 = str1; 92 cout << "str1 is : " << endl; 93 str1.print(); 94 cout << "str2 is : " << endl; 95 96 str2.print(); 97 cout << "str3 is : " << endl; 98 str3.print(); 99 } 100 101 102 int main() 103 { 104 test1(); 105 test2(); 106 test3(); 107 system("pause"); 108 return 0; 109 }
勿在浮沙筑高台