c++ 赋值运算符的重载

  1 #include <cstring>
  2 #include <iostream> // 标准的输入输出
  3 using namespace std;
  4 
  5 class Person {
  6 public:
  7     // 系统默认提供构造函数、拷贝构造、析构函数、赋值运算符
  8     Person(int a)
  9     {
 10     ¦   this->m_A = a;
 11     }
 12     int m_A;
 13 };
 14 
 15 void test01()
 16 {
 17     Person p1(10);
 18     Person p2(20);
 19     p2 = p1;
 20     cout << p2.m_A << endl;
 21 }
 22 
 23 class Person2 {
 24 public:
 25     Person2(const char* name)
 26     {
 27     ¦   this->m_Name = new char[strlen(name) + 1];
 28     ¦   strcpy(this->m_Name, name);
 29     }
 30     char* m_Name;
 31 
 32     Person2& operator=(Person2& p)
 33     {
 34     ¦   if (this->m_Name != NULL) {
 35     ¦   ¦   delete[] this->m_Name;
 36     ¦   ¦   this->m_Name = NULL;
 37     ¦   }
 38     ¦   this->m_Name = new char[strlen(p.m_Name) + 1];
 39     ¦   strcpy(this->m_Name, p.m_Name);
 40     ¦   return *this;
 41     }
 42     ~Person2()
 43     {
 44     ¦   if (this->m_Name != NULL) {
 45     ¦   ¦   delete this->m_Name;
 46     ¦   ¦   this->m_Name = NULL;
 47     ¦   }
 48     }
 49 };
 50 
 51 void test02()
 52 {
 53     Person2 p3("zhangsan");
 54     Person2 p4("lisi");
 55     // 简单的值传递会引起深浅拷贝问题,需要对赋值运算符重载
 56     p4 = p3;
 57     cout << p4.m_Name << endl;
 58 }
 59 
 60 int main()
 61 {
 62     test01();
 63     test02();
 64     return 0;
 65 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值