编一个程序,用成员函数重载运算符“+”和“-”将两个二维数组相加和相减,要求第一个二维数组的值由构造函数设置,另一个二维数组的值由键盘输入
时间: 2024-05-14 08:15:55 浏览: 181
好的,我理解了你的要求。以下是具体的程序实现:
```c++
#include <iostream>
using namespace std;
class Array2D {
private:
int **arr;
int rows,cols;
public:
Array2D(int m, int n) {
rows = m;
cols = n;
arr = new int *[m];
for (int i = 0; i < m; ++i) {
arr[i] = new int[n];
for (int j = 0; j < n; ++j) {
arr[i][j] = 0; // 初始化为0
}
}
}
Array2D& operator+(Array2D& a2) {
if (a2.rows != rows || a2.cols != cols) {
cout << "两个数组大小不一致,无法相加!" << endl;
exit(0);
}
Array2D *result = new Array2D(rows,cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result->arr[i][j] = arr[i][j] + a2.arr[i][j];
}
}
return *result;
}
Array2D& operator-(Array2D& a2) {
if (a2.rows != rows || a2.cols != cols) {
cout << "两个数组大小不一致,无法相减!" << endl;
exit(0);
}
Array2D *result = new Array2D(rows,cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result->arr[i][j] = arr[i][j] - a2.arr[i][j];
}
}
return *result;
}
void input() {
cout << "请输入 " << rows << " 行 " << cols << " 列的数组:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cin >> arr[i][j];
}
}
}
void display() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
Array2D a(3,3); // 构造函数设置第一个二维数组
a.display();
Array2D b(3,3); // 键盘输入第二个二维数组
b.input();
b.display();
Array2D c = a + b; // 重载运算符实现数组相加
c.display();
Array2D d = a - b; // 重载运算符实现数组相减
d.display();
return 0;
}
```
这个程序实现了一个二维数组类,该类包含了构造函数设置数组、输入数组、输出数组、重载+和-运算符等功能。由于你要求用键盘输入第二个二维数组,所以在主函数中,我定义了一个名为“b”的Array2D对象,并调用其input()函数,该函数用于输入二维数组。
在重载运算符+和-时,首先需要判断两个数组的大小是否一致,如果不一致,则无法相加或相减,程序就会输出一条错误信息。如果两个数组大小合法,则定义一个新的Array2D对象result,用于存放相加或相减后的结果。最后返回result的引用。
你可以先自己体验一下这个程序,在运行过程中如果有任何问题可以随时与我交流。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)