剑指offer面试题1:赋值运算符函数

注意:

  1. 函数的返回类型必须是一个引用,因为只有返回引用,才允许连续赋值
  2. 传入的参数声明为常量引用,可以提高代码效率,同时赋值运算函数内不会改变传入的实例状态
  3. 一定要记得释放实例自身已有的内存,否则程序容易出现内存泄露
  4. 传入的参数和当前的实例是不是同一个实例,如果是同一个,则不用进行赋值操作,直接返回即可。
#include <iostream>
#include <string>

using namespace std;

class CMyString {
public:
  CMyString(char *pData = NULL);
  CMyString(const CMyString &str);
  CMyString &operator=(const CMyString &str);
  void print();
  ~CMyString(void);

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

CMyString::CMyString(char *pData) {
  if (pData == NULL) {
    m_pData = new char[1];
    m_pData[0] = '\0';
  } else {
    int length = strlen(pData);
    m_pData = new char[length + 1];
    strcpy(m_pData, pData);
  }
}

CMyString &CMyString::operator=(const CMyString &str) {
  if (this == &str)
    return *this;
  delete[] m_pData;
  m_pData = NULL;

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

  return *this;
}

void CMyString::print() { cout << m_pData << endl; }

void test1() //普通赋值
{
  cout << "test1() begins:" << endl;
  char *text = "hello world";
  CMyString str1(text);
  CMyString str2;
  str2 = str1;

  cout << "The expected result is: " << text << endl;
  cout << "the actual result is: " << endl;
  str2.print();

  cout << endl;
}

int main(int argc, char const *argv[]) {
  test1();
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值