【C++】数组类案例,实现[ ] 、==、 !=的重载

#pragma once
using namespace std;
class Array
{
    
    
public:
	Array(int length);
	Array(const Array& obj);
	~Array();
public:
	void setData(int index, int value);
	int getData(int index);
	int length();

	int& operator[](int index);
	Array& operator=(const Array& obj);
	bool operator==(const Array& obj);
	bool operator!=(const Array& obj);
private:
	int m_length;
	int* m_space;
};

#include "Array.h"
#include <iostream>
using namespace std;

Array::Array(int length=0)//默认为零,设置空串
{
    
    
	this->m_length = length;
	this->m_space = new int[this->m_length];
}
Array::Array(const Array& obj)
{
    
    
	if (this->m_space != NULL)//释放掉旧的空间
	{
    
    
		this->m_length = 0;
		delete[] this->m_space;
	}
	this->m_length = obj.m_length;
	this->m_space = new int[this->m_length];
	for (int i=0; i < this->m_length; i++)
	{
    
    
		this->m_space[i] = obj.m_space[i];
	}
}
Array::~Array()
{
    
    
	if (this->m_space != NULL)
	{
    
    
		delete[] this->m_space;
		this->m_space = NULL;
		this->m_length = 0;
	}
}
void Array::setData(int index, int value)
{
    
    
	this->m_space[index] = value;
}
int Array::getData(int index)
{
    
    
	return this->m_space[index];
}
int Array::length()
{
    
    
	return this->m_length;
}
//重载[]
int& Array::operator[](int index)
{
    
    
// 	if (index >= this->m_length)
// 	{
    
    
// 		cout << "索引超过数组的长度" << endl;
// 	}
	//由于还不会抛出一个异常,先不写
	return this->m_space[index];
}
//重载等号=
Array& Array::operator=(const Array& obj)
{
    
    
	if (this->m_space!=NULL)
	{
    
    
		delete[] this->m_space;
		this->m_space = NULL;
		this->m_length = 0;
	}
	this->m_length = obj.m_length;
	this->m_space = new int[this->m_length];
	for (int i = 0; i < this->m_length; i++)
	{
    
    
		this->m_space[i] = obj.m_space[i];
	}
	return *this;
}
bool Array::operator==(const 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!=(const Array& obj)
{
    
    
	return !(*this == obj);
}

void main()
{
    
    	
	Array a(1);
	Array b(10);
	Array c = b;
	c[0] = 1;
	cout << c[0] << endl;

	a = b = c;

	if (a==b)
	{
    
    
		cout << "相等" << endl;
	}
	else
	{
    
    
		cout << "不相等" << endl;
	}
	if (a!=c)
	{
    
    
		cout << "不相等" << endl;
	}
	else
	{
    
    
		cout << "相等" << endl;
	}
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/YJYS_ZHX/article/details/114462206