当时我们编译可以通过,但是运行会出错,因为对象s1与s2进行赋值时,采用浅拷贝,导致对象析构时会对同一块内存空间析构两次。也就是说等号操作符“=”,默认是进行浅拷贝,我们需要对等号操作符进行重载,使其能够进行深拷贝。
同时要重载等号操作符支持链式编程,类如 s3 = s4 = s5; //操作符使对象连载叠加,与上一篇的return *this 与 return this已经介绍过如何返回对象本身。而不是克隆。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<string.h>
#include<windows.h>
using namespace std;
class student
{
public:
student()
{
//默认构造函数
cout << "This is studnt();" << endl;
this->id = 0;
this->name = NULL;
}
student(int id, const char *name)
{
this->id = id;
//深拷贝构造
int len = strlen(name);
this->name = new char[len + 1];
strcpy(this->name, name);
}
student(const student &another)
{
//拷贝构造
this->id = another.id;
int len = strlen(another.name);
this->name = new char[len + 1];
strcpy(this->name, another.name);
}
student & operator=(const student &another)
{
// 1.防止自身赋值
if (this == &another)
{
return *this;
}
// 2. 给自己额外开辟的内存空间释放掉
if (this->name != NULL)
{
delete[] this->name;
this->name = NULL;
this->id = 0;
}
//3. 执行深拷贝
this->id = another.id;
int len = strlen(another.name);
this->name = new char[len + 1];
strcpy(this->name, another.name);
return *this;
}
void printf_id_name()
{
cout << "id= " << id << " name= " << name << endl;
}
~student()
{
if (this->name != NULL)
{
delete[] this->name;
this->name = NULL;
this->id = 0;
}
}
private:
int id;
char *name;
};
int main(void)
{
student s1(1, "C++");
student s2;
student s3(3, "ZJD666");
s2=s3; //深拷贝 等号操作符重载
s1.printf_id_name();
s2.printf_id_name();
s3.printf_id_name();
cout <<" --------------------------" << endl;
student s4(4, "Hello World!");
student s5(5, "Hello C++!");
s3 = s4 = s5; //操作符连载
s3.printf_id_name();
system("pause");
return 0;
}