首页 > 其他 > 详细

剑指offer习题集

时间:2015-08-01 23:24:56      阅读:270      评论:0      收藏:0      [点我收藏+]

1.重载赋值运算符函数:(具体见代码)

//普通做法
CMyString& CMyString::operator=(const CMyString& str)
{
    if (this == &str) 
        return *this;

    delete[] m_Pdata;
    m_Pdata = new char[strlen(str.m_Pdata)+1];
    strcpy(m_Pdata,str.m_Pdata);

    return *this;
}

//更加安全的做法,普通做法在new内存不足情况下,已经将原值delete
CMyString& CMyString::operator=(const CMyString& str)
{
    if (this != &str)
    {
        CMyString strTemp(str);

        char* temp = str.m_Pdata;
        //通过strTemp的析构函数delete掉原值
        strTemp.m_Pdata = m_Pdata; 
        m_Pdata = temp; 
    }

    return *this;
}

 

剑指offer习题集

原文:http://www.cnblogs.com/jason1990/p/4694821.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!