定义一个MyArray类,内部有私有成员int size和int *ptr。
输入描述先输入变量n,创建一个MyArray对象,其对应的数组有n个元素
输出描述根据样例输出
提示你需要提交除了main函数之外的其他代码。
样例输入
5
1 2 3 4 5
样例输出
1,2,3,4,5
2,3,4,5,6
3,5,7,9,11
1,1,1,1,1
70
#include<iostream>
using namespace std;
#define null 0
class MyArray {
private:
int size;
int* ptr;
public:
MyArray() { size = 0; ptr = null; }
MyArray(int size)
{
this->size = size;
ptr = new int[size];
}
MyArray(const MyArray& a)
{
size = a.size;
ptr = new int[size];
for (int i = 0; i < size; i++)
{
ptr[i] = a.ptr[i];
}
}
~MyArray()
{
delete[]ptr;
}
int getSize() { return size;}
int &operator[](int &index)
{
return this->ptr[index];
}
friend ostream& operator<<(ostream& out, const MyArray& m)
{
for (int i = 0; i < m.size; i++)
{
if (i >=0 && i < m.size - 1)
out << m.ptr[i] << ",";
else
out << m.ptr[i];
}
out << endl;
return out;
}
friend MyArray& operator+(const MyArray& c1, const MyArray& c2)
{
MyArray *c3=new MyArray(c1.size);
for (int i = 0; i < c1.size; i++)
{
c3->ptr[i] = c1.ptr[i] + c2.ptr[i];
}
return *c3;
}
friend int operator*(const MyArray& c1, const MyArray& c2)
{
int num = 0;
MyArray* c3 = new MyArray(c1.size);
for (int i = 0; i < c1.size; i++)
{
c3->ptr[i] = c1.ptr[i] * c2.ptr[i];
num += c3->ptr[i];
}
return num;
}
friend MyArray& operator-(const MyArray& c1, const MyArray& c2)
{
MyArray* c3 = new MyArray(c1.size);
for (int i = 0; i < c1.size; i++)
{
c3->ptr[i] = c1.ptr[i] - c2.ptr[i];
}
return *c3;
}
MyArray& operator=(const MyArray& M)
{
if (ptr)delete[]ptr;
size = M.size;
ptr = new int[size];
for (int i = 0; i < M.size; i++)
ptr[i] = M.ptr[i];
return *this;
}
};