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;
}

猜你喜欢

转载自blog.csdn.net/HAIFEI666/article/details/114896643