#include <iostream>
#include "Array1.h"
Array1::Array1(int length)
{
if (length<0)
{
this->mlength = 0;
}
this->mlength = length;
this->mspace = new int[this->mlength];
}
Array1::Array1(const Array1& obj)
{
this->mlength = obj.mlength;
this->mspace = new int[obj.mlength];
for (int i = 0;i<mlength;i++)
{
this->mspace[i] = obj.mspace[i];
}
}
Array1::~Array1()
{
if (this->mspace!= NULL)
{
delete[] this->mspace;
}
}
int Array1::length()
{
return this->mlength;
}
void Array1::setData(int index,int value)
{
if (index>=this->mlength)
{
return;
}
this->mspace[index] = value;
}
int Array1::getData(int index)
{
if (index>=this->mlength)
{
return -1;
}
return this->mspace[index];
}
Array1& Array1::operator=(const Array1 &obj)
{
//1.释放旧内存
if (this->mspace!=NULL)
{
delete[] this->mspace;
this->mlength = NULL;
this->mlength = 0;
}
//2.根据obj分配新内存
this->mlength = obj.mlength;
this->mspace = new int[obj.mlength];
//3.赋值
for (int i = 0;i<mlength;i++)
{
this->mspace[i] = obj.mspace[i];
}
return *this;
}
//如果函数返回值当左值 需要返回引用
//需要返回引用 元素本身 而不是一个值
int& Array1::operator[](int i)
{
return this->mspace[i];
}
bool Array1::operator==(const Array1 &obj)
{
if (this->mlength != obj.mlength )
{
return false;
}
for (int i = 0;i<mlength;i++)
{
if (this->mspace[i]!= obj.mspace[i])
{
return false;
}
}
return true;
}
bool Array1::operator!=(const Array1 &obj)
{
if (this->mlength != obj.mlength )
{
return true;
}
for (int i = 0;i<mlength;i++)
{
if (this->mspace[i]!= obj.mspace[i])
{
return true;
}
}
return false;
}