LintCode 208. Assignment Operator Overloading (C++ Only)

原题

LintCode 208. Assignment Operator Overloading (C++ Only)

Description

Implement an assignment operator overloading method.

Make sure that:

The new data can be copied correctly
The old data can be deleted / free correctly.
We can assign like A = B = C

Clarification

This problem is for C++ only as Java and Python don't have overloading for assignment operator.

Example

If we assign like A = B, the data in A should be deleted, and A can have a copy of data from B.
If we assign like A = B = C, both A and B should have a copy of data from C.

代码

class Solution {
public:
    char *m_pData;
    Solution() {
        this->m_pData = NULL;
    }
    Solution(char *pData) {
        if (pData) {
            m_pData = new char[strlen(pData) + 1];
            strcpy(m_pData, pData);
        } else {
            m_pData = NULL;
        }
    }

    // Implement an assignment operator
    Solution operator=(const Solution &object) {
        // write your code here
        // if (m_pData) delete[] m_pData;
        if (this == &object) return *this;
        if (object.m_pData) {
            if (m_pData) delete[] m_pData;
            m_pData = new char[strlen(object.m_pData) + 1];
            strcpy(m_pData, object.m_pData);
        } else {
            m_pData = NULL;
        }
        return *this;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 天道施第八十二 天道施,地道化,人道義。 (吐氣者施,而含氣者化,是以陽施而陰化也) 聖人見端而知本,精之至也;得...
    林风起阅读 4,673评论 0 0
  • 如果你已经有了好的爱情,甚至好的婚姻,那么,很真诚的恭喜你,你的一切的顺利和幸运也有次开始了。 一份好的爱情,是你...
    er新心弍阅读 2,415评论 0 1
  • 我知道写作有很多的好处,可是写作还是让我很痛苦。 经常半天憋不出一个字,或是写着写着就卡壳儿无法进行下去,或者写完...
    天野丢阅读 3,161评论 0 0
  • 虽然已经是深夜了,街上依旧还有很多人。我坐在公园的草坪上,看着什么也没有的天空。 闭上眼,耳边有车声,有音乐声,偶...
    那只狐狸阅读 1,170评论 2 4
  • 我独爱秋菊 在百花齐放的春天里,她才开始开枝散叶,夏荷盛开的夏天里,她选择了枝繁叶茂的成长 待百花凋谢,草木枯黄的...
    咸小雨阅读 2,890评论 9 9