11.5.4重学C++之【赋值运算符重载】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;



/*
    4.5.4 赋值运算符重载
        C++编译器至少给一个类添加4个函数
            默认构造函数,无参,函数体为空(4.2.4)
            默认析构函数,无参,函数体为空(4.2.4)
            默认拷贝构造函数,对属性进行值拷贝(4.2.4)
            赋值运算符operator=,对属性进行值拷贝(4.5.4新增)

        若类中有属性指向堆区,则做赋值操作时也会出现深浅拷贝问题(4.2.5)
*/



class Person{
public:
    int * age;

    Person(int _age){
        age = new int(_age); // 堆区数据,由程序员手动开辟、手动释放
    }

    ~Person(){
        if(age != NULL){
            delete age;
            age = NULL;
        }
    }

    // 重载赋值运算符=
    Person & operator=(Person & p){
        // 编译器默认提供浅拷贝age = p.age
        // 应先判断是否有属性在堆区,若有则先释放干净,再深拷贝
        if(age != NULL){
            delete age;
            age = NULL;
        }
        age = new int(*p.age); // 深拷贝
        return *this;
    }


};


void test1(){
    Person p1(18);
    cout << "p1年龄:" << p1.age << endl; // 地址
    cout << "p1年龄:" << *p1.age << endl; // 值
    cout << endl;

    Person p2(20);
    cout << "p2年龄:" << *p2.age << endl;
    cout << endl;

    p2 = p1;
    cout << "p1年龄:" << *p1.age << endl;
    cout << "p2年龄:" << *p2.age << endl;
    cout << endl;

    Person p3(30);
    p3 = p2 = p1;
    cout << "p1年龄:" << *p1.age << endl;
    cout << "p2年龄:" << *p2.age << endl;
    cout << "p3年龄:" << *p3.age << endl;
    cout << endl;
}



int main()
{
    test1();

    system("pause");
    return 0;
}

posted @   yub4by  阅读(28)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示