运算符重载

#include<iostream>
#include<string.h>
using namespace std;
//赋值运算符重载,当数据在堆区,编译器提供的浅拷贝逐字节拷贝而可能会导致堆区数据重复释放,代码崩溃
class person{
private:
    friend ostream& operator<<(ostream& cout, const person& p);
        int*  p_age;
public:
    person(int age) {              //解构函数在堆区开辟空间
        p_age = new int(age);
    }
    ~person() {                       //自定义析构函数释
        if (p_age != NULL) {
            delete p_age;
            p_age = NULL;
        }
    } 
    
     person& operator=(const person& p) {
        int* temp = new int(*p.p_age);
        delete this->p_age;
        this->p_age = temp;
        return *this;
    }
            };
ostream& operator<<(ostream& cout, const person& p) {
    cout << (int)p.p_age <<endl   << *p.p_age;
    return cout;
}
void test01() {
    person p1(18);
    person p2(19);
    person p3(20);
    p1 = p2;
    cout <<p1;
}
//关系运算符重载

class student {
    friend ostream& operator<<(ostream& cout, student& p);
    friend void test02();
    int age;
    string name;
public:
    student(int age, string name) {
        this->age = age;
        this->name = name;
    }
        bool operator==(student & p){
        if ((p.age == this->age )&& (p.name == this->name))
            return true;
        return false;
    }
        student& operator=(const student& p) {
            age = p.age;
            
            return *this;
        }
};
ostream& operator<<(ostream& cout, student& p) {
    cout << p.age << endl  << p.name;
    return cout;
}
void test02() {
    student A(13, "张三");
    student B(10, "王二狗");
    A = B;

    if (A == B)
        cout << A.name << "与" << B .name<< "是同一个学生";
    else
        cout << A << endl  << B <<  endl;

}
        int main() {
            //test01();
            test02();
            system("pause");
            return 0;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值