下面是一个Array类定义,实现数组功能,请在类体外为其添加构造函数、复制构造函数、析构函数、赋值运算符函数,下标运算符函数。 class Array {protected: int *mData;//数组数据 int mn;//数组元素个数 public: Array (int n,int value=0); Array (int *data, int n); Array (const Array &b); ~Array( ); int &operator[](int index); Array &oerator=(const Array &b); };
时间: 2024-03-10 09:46:15 浏览: 125
为Array类添加构造函数、复制构造函数、析构函数、赋值运算符函数和下标运算符函数的实现如下:
```cpp
#include <iostream>
using namespace std;
class Array
{
protected:
int* mData; //数组数据
int mn; //数组元素个数
public:
Array(int n, int value = 0)
{
mn = n;
mData = new int[mn];
for (int i = 0; i < mn; i++)
mData[i] = value;
}
Array(int* data, int n)
{
mn = n;
mData = new int[mn];
for (int i = 0; i < mn; i++)
mData[i] = data[i];
}
Array(const Array& b)
{
mn = b.mn;
mData = new int[mn];
for (int i = 0; i < mn; i++)
mData[i] = b.mData[i];
}
~Array()
{
delete[] mData;
}
int& operator[](int index)
{
if (index < 0 || index >= mn)
throw "Out of range!";
return mData[index];
}
Array& operator=(const Array& b)
{
if (&b == this)
return *this;
delete[] mData;
mn = b.mn;
mData = new int[mn];
for (int i = 0; i < mn; i++)
mData[i] = b.mData[i];
return *this;
}
};
int main()
{
int data[] = { 1, 2, 3 };
Array a1(3, 0);
Array a2(data, 3);
a1 = a2;
cout << a1[0] << " " << a1[1] << " " << a1[2] << endl;
cout << a2[0] << " " << a2[1] << " " << a2[2] << endl;
return 0;
}
```
阅读全文