C++ 45 之 赋值运算符的重载

cpp 复制代码
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

class Students05{
public:
    int m_age;
    char* m_name;
    Students05(){

    }
    Students05(const char* name,int age){
        // 申请堆空间保存m_name;
        this->m_name = new char[strlen(name) + 1];
        strcpy(this->m_name, name);
        this->m_age = age;
    }
    // 清空堆空间
    ~Students05(){
        if(this->m_name){
            delete[] this->m_name;
            this->m_name = NULL;
        }
    }
    // 重载赋值运算符 = 
    Students05& operator=(const Students05 &p){
        // 先判断原来的堆区是否有内容
        if(this->m_name){
            delete[] this->m_name;
            this->m_name = NULL;
        }

        this->m_name = new char[strlen(p.m_name) + 1];
        strcpy(this->m_name, p.m_name);
        this->m_age = p.m_age;
        return *this;
    }

    // 拷贝构造函数重载。使用深拷贝解决浅拷贝的free问题
    Students05(const Students05 &p){
        this->m_name = new char[strlen(p.m_name) + 1];
        strcpy(this->m_name, p.m_name);
        this->m_age = p.m_age;
    }
};

int main()
{
    // 编译器默认会给类4个默认函数: 默认构造函数、析构函数、拷贝函数、
    // 拷贝赋值运算符(operator=)
    // stu3 = stu2; // 赋值操作 走拷贝赋值运算符(operator=)
    // Students05 stu3 = stu2; //初始化操作,走复制构造函数 // 此时stu3 刚刚创建
    // Students05 stu3 = Students05(stu2); //初始化操作,走复制构造函数



    // Students05 stu1(18);
    // // Students05 stu2 = stu1; // 相当于Students05 stu2 = Students05(stu1);
    // Students05 stu2;
    // stu2 = stu1;

    // cout << stu1.m_age << endl;


    Students05 stu1("张三",18);
    Students05 stu2("四",28);
    // 执行重载函数时 stu1作为Students05& operator=(const Students05 &p)的参数 里面的this 是stu2
    stu2 = stu1;   // 这种写法叫赋值   // 默认是浅拷贝,执行delete的时候会报错,学要深拷贝才可以


    Students05 stu3("王",39);
    stu3 = stu2 = stu1; // 想链式编程,需要返回当前对象

    Students05 stu4 = stu3; // 隐式法 调用的默认拷贝构造函数,我们自己用new在堆空间中申请的内存,清空的时候会出现错误,需要重载拷贝构造函数
    cout << stu1.m_name << stu1.m_age << endl;
    cout << stu2.m_name << stu2.m_age << endl;
    cout << stu3.m_name << stu3.m_age << endl;

    // int a = 10;
    // int b = 20;
    // int c;
    // c = a = b;
    // cout << "a: " << a << endl;
    // cout << "b: " << b << endl;
    // cout << "c: " << c << endl;

    return 0;
}
相关推荐
科技苑6 小时前
C++ CAS与ABA问题详解,无锁编程的经典陷阱怎么解决?
c++·人工智能
czq_26867194877 小时前
Python打卡第46天
开发语言·python
Evand J9 小时前
【MATLAB例程介绍】(17)永磁同步电机(PMSM)基于自适应无迹卡尔曼滤波(AUKF)的电流噪声在线估计。测量噪声协方差自适应与转速估计对比仿真
开发语言·matlab·卡尔曼滤波·无迹卡尔曼滤波·pmsm·电机滤波
BaiPeter10 小时前
ZPL文件预览
开发语言·c++
悠仁さん13 小时前
【C++】哈希表
c++·算法·散列表
Severus_black15 小时前
【C++初阶】list使用及相关实现,思路顺滑流畅!
c语言·数据结构·c++·stl·list
噢,我明白了15 小时前
JAVA中的一些基础应用知识点
java·开发语言
时间的拾荒人16 小时前
Redis 入门详解:核心特性、重要文件与全局命令实战
开发语言·redis·面试
敲上瘾16 小时前
Qt Widgets入门:项目模板解析与Hello World
开发语言·数据库·c++·qt·ui·qt6.3
码途行者18 小时前
网站的SQL 注入:从攻击原理到防御措施
开发语言·sql·php