《剑指offer》第一题(重载赋值运算符)

//重载赋值运算符

#include <iostream>
#include <cstring>
using namespace std;

class CMystring
{
private:
    char* m_pData;//私有变量m_pData

public:
    CMystring(const char* pData = NULL)//具有默认参数的 含参构造函数,注意此处的const
    {
        if (pData != NULL)//注意判断是否是空字符串
        {
            m_pData = new char[strlen(pData) + 1];
            strcpy(m_pData, pData);
        }
        else
            m_pData = NULL;
    }

    CMystring(const CMystring& str)//复制构造函数,注意此处一定是const class_type &,没这个引用是浅复制,容易内存爆炸
    {
        if (str.m_pData != NULL)
        {
            m_pData = new char[strlen(str.m_pData) + 1];
            strcpy(m_pData, str.m_pData);
        }
        else
            m_pData = NULL;
    }

    ~CMystring(void)//析构函数
    {
        delete[] m_pData;//一定释放内存,不然造成内存泄漏
    }

    CMystring& operator= (const CMystring& str)//重载赋值运算符,此处一定要返回类型是引用,不然无法连续赋值,而且参数列表里要用常量引用
    {
        if ((this != &str) && (str.m_pData != NULL))//此处一定判断传入参数和实例是否是一个,不然一旦释放实例,传入参数也被释放了
        {
            if (m_pData != NULL)
                delete[] m_pData;
            m_pData = new char[strlen(str.m_pData) + 1];
            strcpy(m_pData, str.m_pData);
        }
        return *this;//必须返回自身引用,不然无法连续赋值
    }

    void display()
    {
        if (m_pData != NULL)
        {
            cout << m_pData;
        }
    }

};

int main()
{
    CMystring str1;
    CMystring str2("hi");
    CMystring str3("hello");
    str1 = str2;//测试用例一:实例A赋值实例B
    str3 = str3;//测试用例二:实例自身赋值
    str1 = str2 = str3;//测试用例三:实现连续赋值
    str1.display();//这里测试案例写的不好,最好写成void子函数,然后函数内各种cout提示案例实现到哪一步了,这里我有点偷懒
    system("pause");
}

 

posted @ 2019-03-01 19:50  深夜十二点三十三  阅读(392)  评论(0编辑  收藏  举报