#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;
}