```cpp #include <iostream> #include <stdlib.h> using namespace std; class Matrix { private: int row, col; int* m; public: // 构造函数 Matrix(int r = 0, int c = 0) : row(r), col(c) { if (r > 0 && c > 0) { m = new int[r * c]; for (int i = 0; i < r * c; i++) { cin >> m[i]; } } else { m = nullptr; } } // 析构函数 ~Matrix() { if (m != nullptr) { delete[] m; } } // 重载加法运算符 Matrix operator+(const Matrix& other) const { if (row != other.row || col != other.col) { cout << " program terminated! "; exit(1); } Matrix result(row, col); for (int i = 0; i < row * col; i++) { result.m[i] = m[i] + other.m[i]; } return result; } // 重载赋值运算符 Matrix& operator=(const Matrix& other) { if (this == &other) { return *this; } if (row != other.row || col != other.col) { cout << " program terminated! "; exit(1); } for (int i = 0; i < row * col; i++) { m[i] = other.m[i]; } return *this; } // 显示矩阵 void disp(); }; void Matrix::disp() { for (int i = 0; i < row; i++) { cout << '\t'; for (int j = 0; j < col; j++) cout << *(m + i * col + j) << '\t'; cout << endl; } } int main() { int row_a, col_a, row_b, col_b; cin >> row_a >> col_a; Matrix A(row_a, col_a); cin >> row_b >> col_b; Matrix B(row_b, col_b), C; C = A + B; C.disp(); A = B; A.disp(); return 0; } ``` 额外注意的逻辑点 1. 在构造函数中分配内存时,要确保输入的行数和列数是有效的正整数,避免内存分配错误。 2. 重载赋值运算符时,要先检查是否是自我赋值,避免不必要的操作。 3. 析构函数中释放内存时,要先检查指针是否为空,防止重复释放内存导致程序崩溃。 [2025-06-23 15:25:09 | AI写代码神器 | 671点数解答]