下面是一个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 19:46:31 浏览: 19
下面是完整的代码实现:
```
#include<iostream>
using namespace std;
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); //重载下标运算符函数,返回值为int类型引用,可以进行赋值运算符重载
Array &operator=(const Array &b);
};
Array::Array(int n, int value) {
mData = new int[n];
mn = n;
for (int i = 0; i < n; i++) {
mData[i] = value;
}
}
Array::Array(int *data, int n) {
mData = new int[n];
mn = n;
for (int i = 0; i < n; i++) {
mData[i] = data[i];
}
}
Array::Array(const Array &b) {
mData = new int[b.mn];
mn = b.mn;
for (int i = 0; i < mn; i++) {
mData[i] = b.mData[i];
}
}
Array::~Array() {
delete[] mData;
}
int &Array::operator[](int index) {
return mData[index];
}
Array &Array::operator=(const Array &b) {
if (this == &b) {
return *this;
}
delete[] mData;
mData = new int[b.mn];
mn = b.mn;
for (int i = 0; i < mn; i++) {
mData[i] = b.mData[i];
}
return *this;
}
int main() {
int data[5] = {1, 2, 3, 4, 5};
Array arr1(data, 5);
Array arr2(6, 6);
cout << "arr1: ";
for (int i = 0; i < 5; i++) {
cout << arr1[i] << " ";
}
cout << endl;
cout << "arr2: ";
for (int i = 0; i < 6; i++) {
cout << arr2[i] << " ";
}
cout << endl;
arr2 = arr1;
cout << "arr2 after assignment: ";
for (int i = 0; i < 5; i++) {
cout << arr2[i] << " ";
}
cout << endl;
Array arr3(arr1);
cout << "arr3: ";
for (int i = 0; i < 5; i++) {
cout << arr3[i] << " ";
}
cout << endl;
return 0;
}
```
注意:以上代码中,赋值运算符函数和下标运算符函数已经在其中实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)