#ifndef ARRAY_H_INCLUDED
#define ARRAY_H_INCLUDED
#include<iostream>
using namespace std;
class Array
{
public:
int m_length; //数组的长度
int *m_space; //指向数组的指针
public:
Array(int length) //确定数组长度并且给数组分配存储空间
{
this->m_length = length;
m_space = new int[m_length];
}
void setData(int index, int value) //为数组赋值
{
m_space[index] = value;
}
int getData(int i) //返回数组元素str[i]的值
{
return m_space[i];
}
int &operator[](int i) //运算符[]的重载, 返回值做左值,返回一个引用
{
return m_space[i];
}
Array& operator=(Array &temp) //用=进行深拷贝
{
if (this->m_space != NULL) //先清除原来所占的内存
{
delete [] m_space;
m_length = 0;
}
this->m_length = temp.m_length;
this->m_space = new int[m_length];
for (int i = 0; i < m_length; i++)
{
this->m_space[i] = temp[i];
}
return *this;
}
int operator==(Array &temp) //数组相等返回1,否则返回0
{
if (this->m_length != temp.m_length) //先判断两个数组长度是否相等
return 0;
for (int i = 0; i < this->m_length; i++) //判断数组的各个元素是否相等
{
if (this->m_space[i] != temp[i])
return 0;
}
return 1;
}
};
#endif // ARRAY_H_INCLUDED
#include"Array.h"
int main()
{
Array a1(10); //定义数组并分配存储空间
for (int i = 0; i < a1.m_length; i++) //初始化数组
{
a1.setData(i, i);
}
cout << "a1数组元素为:" <<endl;
for (int i = 0; i < a1.m_length; i++) //输出数组的值
{
cout << a1.getData(i) << " ";
}
cout << endl;
// Array a2 = a1;
Array a2(5);
a2 = a1;
a2[2] = 10;
cout << "a1[2]: " << a1[2] << endl;
cout << "a2[2]: " << a2[2] << endl;
cout << "a2数组元素为:" <<endl;
for (int i = 0; i < a2.m_length; i++) //输出数组的值
{
cout << a2.getData(i) << " ";
}
cout << endl;
if (a1 == a2)
cout << "两数组相等" << endl;
else
cout << "两数组不相等" << endl;
return 0;
}
运算符重载
最新推荐文章于 2024-09-09 21:20:50 发布