整形数组相加重载运算符
时间: 2024-06-03 19:04:00 浏览: 18
整形数组相加的重载运算符是指在C++中,可以通过重载"+"运算符来实现两个整形数组的相加操作。具体实现如下:
```cpp
#include <iostream>
class IntArray {
private:
int* array;
int size;
public:
IntArray(int size) {
this->size = size;
array = new int[size];
}
// 重载"+"运算符
IntArray operator+(const IntArray& other) const {
IntArray result(size);
for (int i = 0; i < size; i++) {
result.array[i] = array[i] + other.array[i];
}
return result;
}
// 获取数组元素
int& operator[](int index) {
return array[index];
}
// 输出数组元素
friend std::ostream& operator<<(std::ostream& os, const IntArray& arr) {
for (int i = 0; i < arr.size; i++) {
os << arr.array[i] << " ";
}
return os;
}
};
int main() {
IntArray arr1(5);
IntArray arr2(5);
// 初始化数组元素
for (int i = 0; i < 5; i++) {
arr1[i] = i + 1;
arr2[i] = i + 2;
}
// 使用重载的"+"运算符进行相加操作
IntArray result = arr1 + arr2;
// 输出结果
std::cout << "arr1: " << arr1 << std::endl;
std::cout << "arr2: " << arr2 << std::endl;
std::cout << "result: " << result << std::endl;
return 0;
}
```
运行结果如下:
```
arr1: 1 2 3 4 5
arr2: 2 3 4 5 6
result: 3 5 7 9 11
```
相关推荐
![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)