在类成员变量中含有指针类型时,如果没有自定义一个拷贝构造函数,程序会崩溃。 同样,如果没有自定义=运算符重载函数,也会使得程序运行时崩溃,原因都是因为编译器提供的默认的拷贝构造函数与=运算符重载函数执行的都是浅拷贝。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class Vertify
{
public:
Vertify(const char* name)
{
this->size_ = strlen(name);
this->pName_ = new char[size_ + 1];
strcpy(pName_, name);
}
Vertify(const Vertify & obj)
{
this->size_ = obj.size_;
this->pName_ = new char[size_ + 1];
strcpy(pName_, obj.pName_);
}
void operator= (Vertify & obj)
{
cout << "=运算符重载"<<endl;
this->size_ = obj.size_;
this->pName_ = new char[size_ + 1];
strcpy(pName_, obj.pName_);
}
~Vertify()
{
if (NULL != pName_)
{
delete pName_;
pName_ = NULL;
}
size_ = 0;
}
public:
int size_;
char* pName_;
};
int main()
{
{
Vertify v1("万恶的小日本");
Vertify v2("抗战胜利大阅兵");
v1 = v2;
}
cin.get();
return 0;
}
注:思考下V1= v2后,V1对象原来所分配的内存有没有释放?
解决方案:
在重载=的函数中,先释放内存,再重新开辟内存。
void operator= (Vertify & obj)
{
if (NULL != this->pName_)
{
delete this->pName_;
this->pName_ = NULL;
this->size_ = 0;
}
cout << "=运算符重载"<<endl;
this->size_ = obj.size_;
this->pName_ = new char[size_ + 1];
strcpy(pName_, obj.pName_);
}