用成员函数重载运算符“+”和“-”,将两个二维数组相加和相减,要求第一个二维数组的值由构造函数设置,另一个二维数组的值由键盘输入。用代码实现
时间: 2024-03-05 08:52:24 浏览: 28
好的,以下是代码实现:
```cpp
#include <iostream>
using namespace std;
class TwoDArray {
private:
int **arr;
int rows, cols;
public:
// 构造函数设置第一个数组的值
TwoDArray(int r, int c) {
rows = r;
cols = c;
arr = new int*[rows];
for (int i = 0; i < rows; i++) {
arr[i] = new int[cols];
for (int j = 0; j < cols; j++) {
arr[i][j] = i + j;
}
}
}
// 用于键盘输入第二个数组的值
void input() {
arr = new int*[rows];
for (int i = 0; i < rows; i++) {
arr[i] = new int[cols];
for (int j = 0; j < cols; j++) {
cout << "请输入arr[" << i << "][" << j << "]的值:";
cin >> arr[i][j];
}
}
}
// 重载运算符“+”
TwoDArray operator+(TwoDArray &other) {
TwoDArray result(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.arr[i][j] = arr[i][j] + other.arr[i][j];
}
}
return result;
}
// 重载运算符“-”
TwoDArray operator-(TwoDArray &other) {
TwoDArray result(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.arr[i][j] = arr[i][j] - other.arr[i][j];
}
}
return result;
}
// 显示数组的值
void display() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
TwoDArray arr1(2, 3);
TwoDArray arr2(2, 3);
arr2.input();
cout << "arr1的值:" << endl;
arr1.display();
cout << "arr2的值:" << endl;
arr2.display();
TwoDArray arr3 = arr1 + arr2;
cout << "arr3 = arr1 + arr2 的值:" << endl;
arr3.display();
TwoDArray arr4 = arr1 - arr2;
cout << "arr4 = arr1 - arr2 的值:" << endl;
arr4.display();
return 0;
}
```
使用示例:
```
请输入arr[0][0]的值:1
请输入arr[0][1]的值:2
请输入arr[0][2]的值:3
请输入arr[1][0]的值:4
请输入arr[1][1]的值:5
请输入arr[1][2]的值:6
arr1的值:
0 1 2
1 2 3
arr2的值:
1 2 3
4 5 6
arr3 = arr1 + arr2 的值:
1 3 5
5 7 9
arr4 = arr1 - arr2 的值:
-1 -1 -1
-3 -3 -3
```
阅读全文