定义一个一维数组类Array,实现输入运算符<<的重载(功能为输出数组的内容),输入运算符>>重载(功能为输入数组的内容),并实现以下几个运算符的重载[ ]、+和-功能为该类对象的指定位置数据的加减运算,通过main函数进行验证
时间: 2024-03-01 07:55:11 浏览: 79
好的,下面是符合要求的一维数组类Array的实现。
```c++
#include <iostream>
using namespace std;
class Array {
private:
int* data;
int size;
public:
Array(int s) : size(s) {
data = new int[size];
}
~Array() {
delete[] data;
}
friend ostream& operator<<(ostream& os, const Array& arr) {
for (int i = 0; i < arr.size; ++i) {
os << arr.data[i] << " ";
}
return os;
}
friend istream& operator>>(istream& is, Array& arr) {
for (int i = 0; i < arr.size; ++i) {
is >> arr.data[i];
}
return is;
}
int& operator[](int index) {
if (index >= 0 && index < size) {
return data[index];
}
else {
cerr << "Index out of range!" << endl;
exit(1);
}
}
Array operator+(const Array& arr) {
if (arr.size != size) {
cerr << "Arrays have different sizes!" << endl;
exit(1);
}
Array result(size);
for (int i = 0; i < size; ++i) {
result.data[i] = data[i] + arr.data[i];
}
return result;
}
Array operator-(const Array& arr) {
if (arr.size != size) {
cerr << "Arrays have different sizes!" << endl;
exit(1);
}
Array result(size);
for (int i = 0; i < size; ++i) {
result.data[i] = data[i] - arr.data[i];
}
return result;
}
};
int main() {
Array arr1(5), arr2(5);
cout << "Enter 5 integers for array 1: " << endl;
cin >> arr1;
cout << "Enter 5 integers for array 2: " << endl;
cin >> arr2;
cout << "Array 1: " << arr1 << endl;
cout << "Array 2: " << arr2 << endl;
cout << "The element at index 2 of array 1 is: " << arr1[2] << endl;
cout << "The sum of element at index 2 of array 1 and element at index 3 of array 2 is: " << arr1[2] + arr2[3] << endl;
cout << "The difference between element at index 0 of array 1 and element at index 4 of array 2 is: " << arr1[0] - arr2[4] << endl;
Array arr3 = arr1 + arr2;
Array arr4 = arr1 - arr2;
cout << "Array 1 + Array 2: " << arr3 << endl;
cout << "Array 1 - Array 2: " << arr4 << endl;
return 0;
}
```
在这个例子中,我们定义了一个一维数组类Array,重载了输入运算符<<和输入运算符>>,以及运算符[]、+和-。在main函数中,我们创建了两个Array类型的对象arr1和arr2,通过重载的输入运算符>>为它们赋值,接着输出arr1和arr2的值,以及它们指定位置数据的加减运算结果。最后,我们创建了两个新的Array类型的对象arr3和arr4,分别存储arr1和arr2的加减结果,并对它们进行输出。
希望这个例子能够帮助您理解一维数组类Array的实现。
阅读全文