C++实现矩阵类:重载运算符+与=,含构造、析构及异常处理
```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. 析构函数中释放内存时,要先检查指针是否为空,防止重复释放内存导致程序崩溃。 ######[AI写代码神器 | 671点数解答 | 2025-06-23 15:25:09]
- C++ 实现:轻松计算两个矩阵的乘法并输出结果(字节豆包 | 381点数解答 | 2025-12-03 19:20:23)115
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)349
- CentOS下Java进程出现futex_wait_queue_me问题的处理全流程(阿里通义 | 283点数解答 | 2023-11-20 14:51:26)467
- 替雷利珠单抗致免疫相关性糖尿病:病例报道与机制探讨,为临床用药敲响警钟( | 164点数解答 | 2024-10-11 14:52:52)268
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)319
- Python开发必知://、%、**运算符深度解析(阿里通义 | 317点数解答 | 2023-11-08 00:49:49)973
- Android 开发:Kotlin 中简洁实用的 Elvis 运算符全解析(百度文心 | 231点数解答 | 2023-11-09 17:28:21)271
- Android开发:Kotlin双感叹号(!!)运算符全解析及使用风险(百度文心 | 334点数解答 | 2023-11-09 17:28:33)295
- Python+Tkinter:打造30以内加减乘除随机出题、判题打分GUI小程序(GPT | 1266点数解答 | 2024-06-19 14:45:56)330
- Python 复数类 Complex:前置与后置自增运算符重载全解析(字节豆包 | 357点数解答 | 2025-06-06 17:22:02)133
- Android开发必看:深度解析与有效避免OOM异常的秘籍(百度文心 | 326点数解答 | 2023-11-09 17:33:36)236
- Java 实现自定义异常 CheckNumException 及异常捕获处理(GPT | 626点数解答 | 2024-05-24 09:54:32)240