#include<iostream>
#include<iostream>
using namespace std;
class Array
{
public:
Array(int num) :size(num)
{
if (num)
{
this->pArr = new int[num];
}
}
Array(const Array& a) :size(a.size)
{
if (a.size)
{
this->pArr = new int[a.size];
this->size = a.size;
for (int i = 0; i < a.size; i++)
{
this->pArr[i] = a.pArr[i];
}
}
}
int operator[](int n)
{
return pArr[n];
}
friend istream& operator>>(istream& in, Array& a)
{
for (int i = 0; i < a.size; i++)
{
in >> a.pArr[i];
}
return in;
}
friend ostream& operator<<(ostream& out, Array& a)
{
for (int i = 0; i < a.size; i++)
{
out << a.pArr[i];
}
return out;
}
Array operator+(const Array& a)
{
Array temp(a.size + this->size);
int i = 0;
for (; i < this->size; i++)
{
temp.pArr[i] = pArr[i];
}
for (int k = 0; i < temp.size; i++)
{
temp.pArr[i] = a.pArr[k++];
}
return temp;
}
~Array()
{
delete[] this->pArr;
this->pArr = nullptr;
}
protected:
int* pArr;
int size = 0;
};
/*2.重载实战: 封装一个Array类,实现定长数组的操作
* //以下测试代码要能够成功运行
Array array(4);
for(int i=0;i<array.size();i++)
{
cin>>array[i];
}
for(int i=0;i<array.size();i++)
{
cout<<array[i];
}
//实现数组的连接
Array one(3); //输入1 2 3
cin>>one;
Array two(4); //输入2 3 4
cin>>two;
Array sum=one+two;
cout<<sum<<endl; //打印1 2 3 2 3 4
Array num;
num=sum;
cout<<num<<endl;
*/
int main()
{
Array one(3);
cin >> one;
cout << one << endl;
Array two(3);
cin >> two;
cout << two << endl;
Array three = one + two;
cout << three;
while (1);
return 0;
}
自写Array类
最新推荐文章于 2024-08-30 16:00:44 发布