剑指offer 面试题1

题目:赋值运算符函数

写出一个类的赋值运算符。
注意事项:
1.是否返回该类的引用类型

2.是否传入的参数类型是常量引用。

3.是否释放自身已有内存

4.是否是同一实例

代码如下:

#include
using namespace std;

class CMyString
{
public:
    CMyString(char *pData=NULL);
    CMyString(CMyString &str);
    CMyString& operator=(CMyString &str);
    ~CMyString(void);
    void Print(){ cout << m_pData; }
private:
    char* m_pData;

};

CMyString::CMyString(char *pData)
{
    if (NULL == pData)
    {
        m_pData = NULL;
        return;
    }
    else
    {
        unsigned int len = strlen(pData)+1;
        m_pData = new char[len];
        for (int i = 0; i < len-1; i++)
            m_pData[i] = pData[i];
        m_pData[len-1] = '\0';
    }
}

CMyString::CMyString(CMyString &str)
{
    unsigned int len = strlen(str.m_pData) + 1;
    m_pData = new char[len];
    for (int i = 0; i < len-1; i++)
        m_pData[i] = str.m_pData[i];
    m_pData[len-1] = '\0';
}

CMyString & CMyString::operator=(CMyString &str)
{
    if (this == &str)
        return *this;
    else
    {
        unsigned int len = strlen(str.m_pData) + 1;
        char *pTemp = new char[len];
        for (int i = 0; i < len-1; i++)
            pTemp[i] = str.m_pData[i];
        pTemp[len-1] = '\0';

        delete[]m_pData;

        m_pData = pTemp;

    }
    return *this;
}

CMyString::~CMyString()
{
    delete [] m_pData;
}

int main()
{
    char c1[10] = "majunfu";
    CMyString s1(c1);
    CMyString s2 = s1;
    s1 = s2;
    s1.Print();
    s2.Print();
    return 0;
}

你可能感兴趣的:(剑指offer)