#include <iostream>
using namespace std;
/****************************************************************************
当类中有指针变量时候,需要重载赋值操作符,因为编译器的赋值操作只是简单的值赋值,
会导致对象消亡时调用析构函数释放2次同一片内存,而另外的对象的内存没有释放,造成内存泄漏
**********************************************************************************/
class Array
{
private:
int length;
int *mspace;
public:
Array(){}
~Array();
Array(int length);
int getlength();
int &operator[](int i); //返回整形的引用,可以当作左值和右值使用
Array& operator=(const Array& obj); //返回类的引用,可以当作左值和右值使用
bool operator==(const Array& obj);
bool operator!=(const Array& obj);
};
Array::Array(int length)
{
this->length = length;
mspace = new int[length];
}
Array::~Array()
{
delete[] mspace;
}
int &Array::operator[](int i)
{
return mspace[i];
}
int Array::getlength()
{
return length;
}
Array& Array::operator=(const Array& obj)
{
delete[] mspace;
length = obj.length;
mspace = new int[length];
for (int i=0; i<length; i++)
{
mspace[i] = obj.mspace[i];
}
return *this;
}
bool Array::operator==(const Array& obj)
{
bool ret = true;
if (length == obj.length)
{
for (int i=0; i<length; i++)
{
if (mspace[i] != obj.mspace[i])
{
ret = false;
}
}
}else
{
ret = false;
}
return ret;
}
bool Array::operator!=(const Array& obj)
{
return !(*this == obj);
}
int main(int argc, char *argv[])
{
Array a1(10);
Array a2(0);
Array a3(0);
int i;
if (a1 != a2)
{
cout<<"a1 != a2"<<endl;
}
for (i=0; i<10; i++)
{
a1[i] = i + 1;
cout<<"a1: "<<a1[i]<<endl;
}
a3 = a2 = a1;
if (a1 == a2)
{
cout<<"a1 == a2"<<endl;
}
for (i=0; i<10; i++)
{
cout<<"a2: "<<a2[i]<<endl;
}
return 0;
}
本文详细介绍了在C++类中处理指针变量时,如何正确重载赋值操作符以避免内存泄漏问题。通过实例展示了如何实现类的赋值操作,确保内存资源的有效管理。
434

被折叠的 条评论
为什么被折叠?



