//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");
}