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