在数组类中重载[ ], =, ==, !=

// Array.h

#pragma once

#include "iostream"
using namespace std;

class Array
{
private:
	int m_length;
	int *m_space;

public:
	Array(int length);
	~Array();
	Array(Array const &obj);
	int length();
	int getArray(int index);
	void setArray(int index, int value);
	int &operator[](int i);
	Array & operator=(Array &obj);   //重载=
	bool operator==(Array &obj);       //重载==
	bool operator!=(Array &a2);     //重载  !=
};
// Array.cpp


#include "Array.h"

Array :: Array(int length)
{
	if (length < 0)   //容错处理
	{
		length = 0;
		m_space = new int[m_length];
	}

	m_length = length;
	m_space = new int[m_length];
}
Array :: ~Array()
{
	if (m_space != NULL)
	{
		delete[] m_space;
		m_length = 0;
	}
}
Array::Array(Array const &obj)
{
	int num;
	m_length = obj.m_length;
	m_space = new int[m_length];
	for (num = 0; num < m_length; num++)
	{
		m_space[num] = obj.m_space[num];
	}
}
int Array::length()
{
	return m_length;
}
int Array :: getArray(int index)
{
	return m_space[index];
}
void Array :: setArray(int index, int value)
{
	m_space[index] = value;
}

// 重载[ ] 
int &Array :: operator[](int i)
{
	return m_space[i];
}

//重载 = 
Array & Array :: operator=(Array &obj)
{
	int i;
	if (this->m_space != NULL)
	{
		delete[] this->m_space;
		this->m_length = 0;
	}
	this->m_space = new int[obj.m_length];
	this->m_length = obj.m_length;
	for (i = 0; i < (this->m_length); i++)
	{
		this->m_space[i] = obj.m_space[i];
	}

	return *this;
}

// 重载==
bool Array:: operator==(Array &obj)
{
	if (this->m_length != obj.m_length)
	{
		return false;
	}
	for (int i = 0; i < this->m_length; i++)
	{
		if (this->m_space[i] != obj.m_space[i])
		{
			return false;
		}
	}
	return true;
}

//重载!=
bool Array :: operator!=(Array &obj)
{
	/*     //正常写法
	if (this->m_length != obj.m_length)
	{
		return true;
	}
	for (int i = 0; i < this->m_length; i++)
	{
		if (this->m_space[i] != obj.m_space[i])
		{
			return true;
		}
	}
	return false;
	*/

	//因为已经重载过 == 
	//这样写更简单!
	return !(*this == obj);         
}

//main.cpp


#include "iostream"
using namespace std;

#include "Array.h"

void main()
{
	Array a1(10);       //设置长度为10
	Array a2(20);
	Array a3(30);
	
	
	int i;
	for (i = 0; i < a1.length(); i++)
	{
	//	a1.setArray(i, i);
		a1[i] = i;                      //运算符重载  int &Array :: operator[](int i)  返回int & ,  所以可以当左值。
		                                   //函数返回值当左值,必须返回一个引用
	}
	a2 = a1;
	
	for (i = 0; i < a1.length(); i++)
	{
	//	cout << a1.getArray(i) << " ";
		cout << a1[i] << " ";
	}
	cout << endl;

	for (i = 0; i < a2.length(); i++)
	{
		//	cout << a1.getArray(i) << " ";
		cout << a2[i] << " ";
	}
	cout << endl;

	//3
	if (a1 == a2)
	{
		cout << "相等" << endl;
	}

	//4
	for (i = 0; i < a3.length(); i++)
	{
		//	a1.setArray(i, i);
		a3[i] = i;                      //运算符重载  int &Array :: operator[](int i)  返回int & ,  所以可以当左值。
		//函数返回值当左值,必须返回一个引用
	}

	if (a1 != a3)
	{
		cout << "不相等" << endl;
	}


	system("pause");
}

 

你可能感兴趣的:(在数组类中重载[ ], =, ==, !=)