#include“”
#pragma once
#include<iostream>
using namespace std;
class Array
{
public:
Array(int length);
Array(const Array&obj );
~Array();
public:
void setData(int index,int valude);
int getData(int index);
int length();
public:
//函数返回至当左值 需要返回一个引用
int& operator[](int i);//[]操作符重载
//重载等号操作符
Array& operator=(Array &a1);
//重载==号操作符
bool operator==(Array &a1);
//重载 !=
bool operator != (Array &a1);
protected:
private:
int m_length;
int *m_space;
};
#include“MyArray.cpp”
#include "MyArray.h"
Array::Array(int length)
{
if (length < 0)
{
length = 0;
}
m_length =length;
m_space = new int[m_length];
}
//Array a2 = a1;
Array::Array(const Array&obj )
{
this->m_length = obj.m_length;
this->m_space = new int [this->m_length];// 分配内存空间
for (int i=0;i<m_length;i++)//数据元素赋值
{
this->m_space[i] = obj.m_space[i];
}
}
Array::~Array()
{
if (m_space != NULL)
{
delete[] m_space;
m_length = 0;
}
}
//a1.setData(i,i);
void Array::setData(int index,int valude)
{
m_space[index] = valude;
}
int Array::getData(int index)
{
return m_space[index];
}
int Array::length()
{
return m_length;
}
int& Array::operator[](int i)
{
return m_space[i];
}
Array& Array::operator=(Array &a1)
{ //1:释放原来的空间
if(this->m_space != NULL)
{
delete [] m_space;
m_length = 0;
}
//2:根据a1的大小 分配内存空间
m_length = a1.m_length;
m_space = new int[a1.m_length];
//3:copy数据
for (int i= 0;i<m_length;i++)
{
/*m_space[i] = a1.m_space[i];*/
m_space[i] = a1[i];
}
return *this;
}
bool Array::operator==(Array &a1)
{
if (this->m_length != a1.m_length)
{
return false;
}
for (int i=0;i<m_length;i++)
{
if(this->m_space[i] != a1[i])
{
return false;
}
}
return true;
}
bool Array::operator != (Array &a1)
{
//if (*this == a1)
//{
// return true;
//}
//else
//{
// return false;
//}
return !(*this == a1);
}
Test_Array2.cpp
#include<iostream>
using namespace std;
#include "MyArray.h"
//类的框架设计设计完毕
//类的测试案例
//重载下标操作符
//重载三个
int main()
{
Array a1(10);
for (int i=0;i<a1.length();i++)
{
a1.setData(i,i);
//1:需要优化的点
a1[i] = i;//报错
//函数返回至当左值 需要返回一个引用
//a1.operator[i]
}
cout<<"输a1: "<<endl;
for (int i=0;i<a1.length();i++)
{
//cout<<a1.getData(i)<<" "<<endl;
//2:需要优化的点
cout<<a1[i]<<endl;
}
//void operator[](int i)
//int operator[](int i)
//int& operator[](int i)
Array a2 = a1;
cout<<"输a2:"<<endl;
for (int i=0;i<a1.length();i++)
{
cout<<a1.getData(i)<<" "<<endl;
}
Array a3(5);
//3:需要优化的地方
{
a3 = a1;
a3 = a2 = a1;
//a3.operator=(a1)
//Array& operator=(Array &a1)
cout<<"打印数组a3"<<endl;
for (int i=0;i<a3.length();i++)//数据元素赋值
{
cout<<a3[i]<<" ";
}
}
//4:需要优化的地方
if (a3 == a1)
{
printf("相等\n");
}
else
{
printf("不相等\n");
}
if (a3 != a1)
{
printf("不相等\n");
}
else
{
printf("相等\n");
}
/*bool operator != (Array &a1);*/
//a3.operator!=(a1);
//a3.operator==(a1)
//bool operator==(Array &a1);
system("pause");
return 0;
}