#include<iostream>
using namespace std;
class Array {
public:
Array(int m_length); //构造函数
Array(const Array& obj); //拷贝构造函数
~Array(); //析构函数
int length(); //求取数组长度
//a1[i] = i 需要重载[]操作符
int &operator[](int i);
Array &operator=(Array a1);
bool operator==(Array& a1);
bool operator!=(Array& a1);
private:
int m_length;
int* m_space;
};
// 构造函数
Array::Array(int m_length) {
this->m_length = m_length;
this->m_space = new int[m_length];
}
// 拷贝构造函数
Array::Array(const Array& obj) {
this->m_length = obj.m_length;
m_space = new int[m_length];
for (int i = 0; i < obj.m_length; i++) {
this->m_space[i] = obj.m_space[i];
}
}
//析构函数
Array::~Array() {
if (this->m_space != NULL) {
delete[] m_space;
this->m_space = NULL;
m_length = 0;
}
}
//求数组的长度
int Array::length() {
return this->m_length;
}
// 重载[]操作符, 函数返回值做左值, 需要返回一个引用
int& Array::operator[](int i) {
return this->m_space[i];
}
// 执行数组的深拷贝
Array& Array::operator=(Array a1) {
if (this->m_space != NULL) {
delete[] m_space;
this->m_space = NULL;
this->m_length = 0;
}
this->m_length = a1.m_length;
this->m_space = new int[a1.m_length];
for (int i = 0; i < a1.m_length; i++) {
this->m_space[i] = a1.m_space[i];
}
return *this;
}
// 判断两个数组是否相等
bool Array::operator==(Array& a1) {
if (this->m_length != a1.m_length) {
return false;
}
for (int i = 0; i < a1.m_length; i++) {
if (this->m_space[i] != a1.m_space[i]) {
return false;
}
}
return true;
}
// 重载 != 运算符, 判断两个数组是否不相等
bool Array::operator!=(Array& a1) {
if (this->m_length != a1.m_length) {
return true;
}
for (int i = 0; i < a1.m_length; i++) {
if (this->m_space[i] != a1.m_space[i]) {
return true;
}
}
return false;
}
int main()
{
Array a1(10);
for (int i = 0; i < a1.length(); i++)
{
//a1.setData(i, i);
//2
a1[i] = i; //需要重载[]运算符
//
//函数返回值当左值,需要返回一个引用
//a1.operator [i]
}
cout << "\n打印数组a1: ";
for (int i = 0; i < a1.length(); i++)
{
//cout<<a1.getData(i)<<" ";
//1
cout << a1[i] << endl;
}
cout << endl;
Array a2 = a1;
//cout << "\n打印数组a2: ";
//for (int i = 0; i < a2.length(); i++)
//{
// cout << a2.getData(i) << " ";
//}
//cout << endl;
//3
Array a3(5);
{
a3 = a1; //重载=运算符
a3 = a2 = a1;
cout << "\n打印数组a3: ";
for (int i = 0; i < a3.length(); i++)
{
cout << a3[i] << " ";
}
//a3.operator=(a1)
//Array& operator=(Array &a1)
}
//功能4
if (a3 == a1)
{
printf("相等\n");
}
else
{
printf("不相等\n");
}
//a3.operator==(a1);
//bool operator==(Array &a1);
if (a3 != a1)
{
printf("不相等\n");
}
else
{
printf("相等\n");
}
//
a3.operator!=(a1)
bool operator!=(Array &a1);
cout << "hello..." << endl;
system("pause");
//return;
}