#include <iostream>
using namespace std;
class Date
{
int y,m,d;
public:
//构造
Date(int y =1900,int m = 1,int d =1):y(y),m(m),d(d)
{
cout << "Date(i,i,i) Constructor," << "this:" << this << endl;
}
//拷贝构造
Date(const Date& d)
{
y = d.y;
m = d.m;
this->d = d.d;
cout << "Date(const Date& d) copy" << "this:" << this << endl;
}
//析构
~Date()
{
cout << "~Date() Destructor," << "this:" << this << endl;
}
};
class Emp
{
string name;
Date* birth;
double salary;
public:
//构造
Emp(string n,int y, int m ,int d , double s):name(n),salary(s)
{
birth = new Date(y,m,d);
cout << "Emp(string,i,i,i,d) Constructor," << "this:" << this << endl;
}
//拷贝构造
Emp(const Emp& e)
{
cout << "Emp(const Emp& e) copy" << "this:" << this << endl;
name = e.name;
salary = e.salary;
birth = new Date(*e.birth); //拷贝来构造
}
// //重载赋值=
// Emp& operator=(const Emp&e)
// {
// //修改此处
// name = e.name;
// //birth = e.birth;
// //用的拷贝构造,还是有问题
// birth = new Date(*e.birth);
// salary = e.salary;
// return *this;
// }
Emp& operator=(const Emp& e)
{
//比较完整的赋值重载,几乎是固定的。
//1. 判断是否是自赋值
//如果注释掉if语句,那么第三个阶段就会有问题
if (this == &e)
{
return *this;
}
//2.释放原来的内存空间
delete birth;
//2.申请新的内存空间
birth = new Date(*e.birth);
//4.拷贝数据
name = e.name;
salary = e.salary;
//5.返回当前对象
return *this;
}
//析构
~Emp()
{
delete birth;
cout << "~Emp() Destructor," << "this:" << this << endl;
}
};
int main()
{
Emp e1("王五",2000,2,2,22222); //构造
Emp e2 = e1; //拷贝构造
Emp e3("",1,1,1,1); //没有空参构造函数,Emp e3; 不行
//第一个e3永远没有机会释放
e3 = e1; // e3.operator=(e1);
}
/*
Date(i,i,i) Constructor,this:0x9158020
Emp(string,i,i,i,d) Constructor,this:0xbfd4fb90
Emp(const Emp& e) copythis:0xbfd4fb80
Date(const Date& d) copythis:0x9158030
Date(i,i,i) Constructor,this:0x9158040
Emp(string,i,i,i,d) Constructor,this:0xbfd4fb70
~Date() Destructor,this:0x9158040
Date(const Date& d) copythis:0x9158040
~Date() Destructor,this:0x9158040
~Emp() Destructor,this:0xbfd4fb70
~Date() Destructor,this:0x9158030
~Emp() Destructor,this:0xbfd4fb80
~Date() Destructor,this:0x9158020
~Emp() Destructor,this:0xbfd4fb90
*/
重载赋值运算符详细
最新推荐文章于 2024-04-25 18:40:56 发布