c++超基础:操作符重载下(重载符号:=、[]、==、!=)示例


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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值