JZ-C-01

剑指offer代码实现:基本照敲,顺便写写注释和疑问。

第一题:为CMyString类添加赋值运算符函数,代码如下:

 1 //============================================================================
 2 // Name        : JZ-C-01.cpp
 3 // Author      : Laughing
 4 // Version     :
 5 // Copyright   : Your copyright notice
 6 // Description : Hello World in C++, Ansi-style
 7 //============================================================================
 8 #include "stdafx.h"
 9 #include <string.h>
10 using namespace std;
11 /**
12  *剑指offer面试题1
13  */
14 class CMyString {
15 public:
16     CMyString(char* pData = NULL); //构造函数
17     CMyString(const CMyString &str); //类似复制构造函数?
18     ~CMyString(void);
19     void print(); //打印
20     CMyString& operator =(const CMyString &str); //赋值运算符重载:返回类型是该类型的引用,这样才可以允许连续赋值:"str=str1=str2"。const:因为在赋值运算符函数内不会改变传入的实例的状态
21 private:
22     char* m_pData;
23 };
24 CMyString::CMyString(char *pData) {
25     if (pData == NULL) { //若为空
26         m_pData = new char[1];
27         m_pData = ''; //字符串默认最后一位补''
28     } else {
29         int length = strlen(pData); //字符串长度
30         m_pData = new char[length + 1]; //为何+1?
31         strcpy(m_pData, pData); //复制
32     }
33 }
34 CMyString::CMyString(const CMyString &str) {
35     int length = strlen(str.m_pData);
36     m_pData = new char[length + 1];
37     strcpy(m_pData, str.m_pData);
38 }
39 CMyString::~CMyString() {
40     delete[] m_pData; //释放内存
41 }
42 void CMyString::print() {
43     cout << m_pData << endl;
44 }
45 CMyString& CMyString::operator =(const CMyString& str) { //自动生成,前面有inline,为什么?
46     if (this == &str) { //先判断传入的参数和当前实例是不是同一个实例★
47         return *this;
48     }
49     /*若没上面的if判断,若为同一个实例,一旦释放自身的内存,传入的参数的内存同样被释放*/
50     delete[] m_pData; //先释放内存
51     m_pData = NULL;
52     m_pData = new char[strlen(str.m_pData) + 1]; //重新分配空间
53     strcpy(m_pData, str.m_pData);
54     return *this; //返回实例自身的引用
55 }
56 int main() {
57     cout << "Hello World!!!" << endl; // prints Hello World!!!
58     char* str = "Hello World"; //有什么问题,和不加 const区别
59     CMyString test(str);
60     test.print();
61     CMyString test2, test3;
62     //test = test; //赋值给自己,此处以判断传入参数和当前实例相同时会不会出现问题
63     test3 = test2 = test; //利用赋值运算符为对象test2,test3赋值
64     test3.print();
65     return 0;
66 }
—————————————————————————————————————行走在人猿的并行线——Laughing_Lz
原文地址:https://www.cnblogs.com/Laughing-Lz/p/5490869.html