C++ =、[ ]、==、!=的重载

//Array.h
#pragma once

#include<iostream>
using namespace std;

class Array
{
public:
	Array(int length);
	Array(const Array& obj);
	~Array();
public:
	void setdata(int index, int data);
	int getdata(int index);
	int getlength();
	int& operator[](int i);
	Array& operator=(Array &t1);
	bool operator==(Array &t);
	bool operator!=(Array &t);
private:
	int m_lentgh;
	int *m_space;
};
//array.cpp
#include"Array.h"
	
Array::Array(int length)//有参构造函数
{
	if (length < 0)
	{
		length = 0;
		m_space = new int[m_lentgh];
	}
	m_lentgh = length;
	m_space = new int[m_lentgh];
}
Array::Array(const Array& obj)//拷贝构造函数
{
	this->m_lentgh = obj.m_lentgh;
	this->m_space = new int[m_lentgh];
	for (int i = 0; i < m_lentgh; i++)
	{
		this->m_space[i] = obj.m_space[i];
	}
}
Array::~Array()//析构函数
{
	if (m_space != NULL)
	{
		delete[] m_space;
		m_space = NULL;
	}
}
//t1.setdata(i,i)
void Array::setdata(int index, int data)
{
	m_space[index] = data;
}
int Array::getdata(int index)
{
	return m_space[index];
}
int Array::getlength()
{
	return m_lentgh;
}
int& Array::operator[](int i)
{
	return m_space[i];
}
Array& Array::operator=(Array &t1)//=的重载
{
	if (this->m_space != NULL)
	{
		delete[] this->m_space;
	}
	this->m_lentgh = t1.m_lentgh;
	this->m_space = new int[m_lentgh];
	for (int i = 0; i < m_lentgh; i++)
	{
		this->m_space[i] = t1.m_space[i];
	}
	return *this;
}
bool Array::operator==(Array &t)//==的重载
{
	if (this->m_lentgh != t.m_lentgh)
	{
		return false;
	}
	for (int i = 0; i < this->m_lentgh; i++)
	{
		if (this->m_space[i] != t.m_space[i])
		{
			return false;
		}
	}
	return true;
}
bool Array::operator!=(Array &t)//!=的重载
{
	if (this->m_lentgh != t.m_lentgh)
	{
		return true;
	}
	for (int i = 0; i < t.m_lentgh; i++)
	{
		if (m_space[i] != t.m_space[i])
		{
			return true;
		}
	}
	return false;
}
//main.h
#include<iostream>
#include"Array.h"
using namespace std;

int main()
{
	Array t1(10);
	for (int i = 0; i < t1.getlength(); i++)
	{
		t1[i] = i;
	}
	/*for (int i = 0; i < t1.getlength(); i++)
	{
		cout << "t1="<<t1.getdata(i)<< endl;
	}*/

	Array t2(t1);
	for (int i = 0; i < t2.getlength(); i++)
	{
		cout << t2[i]<< endl;
	}

	Array t3(5);
	Array t4(10);
	t3 = t1;
	t3 = t4 = t1;
	for (int i = 0; i < t3.getlength(); i++)
	{
		cout << t3[i]<<" ";
	}

	Array t5(5);
	for (int i = 0; i < t5.getlength(); i++)
	{
		t5[i] = i;
	}
	Array t6(t5);
	if (t5 == t6)
	{
		cout << "相等"<< endl;
	}


	if (t3 != t6)
	{
		cout << "不相等"<< endl;
	}
	for (int i = 0; i < t5.getlength(); i++)
	{
		cout << t5[i] << " ";
	}
	
	system("pause");
}

 

  • 13
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值