1. 赋值运算符函数

https://github.com/zhulintao/CodingInterviewChinese2/blob/master/01_AssignmentOperator/AssignmentOperator.cpp

题目:

为 CMyString 类型添加赋值运算符函数

note:

  • 把3返回值的类型声明为该类型的应用,并在函数结束前返回实例自身的引用(*this)
  • 把传入的参数类型声明为常量引用
  • 释放实例自身已有的内存
  • 判断传入的参数和当前的实例是不是同一个实例,如果是同一个,则不进行赋值操作直接返回。

normal approach:

CMyString& CMyString::operator = (const CMyString &str) //1./2.{
    if (this == &str) return *this;  //4

    delete []m_pData; //????  3
    m_pData = nullptr;

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

    return *this;
}

futhermore:

it's not my deal, pass it, fine!

原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11237424.html