定义一个Matrix类,实现矩阵的加法和乘法
时间: 2024-03-25 22:37:50 浏览: 23
好的,以下是一个简单的Matrix类的定义,实现了矩阵的加法和乘法。
```
class Matrix {
private:
int rows, cols;
vector<vector<int>> mat;
public:
// 构造函数
Matrix(int r, int c) : rows(r), cols(c) {
mat.resize(rows, vector<int>(cols, 0));
}
// 加法
Matrix operator+(const Matrix& other) const {
if (rows != other.rows || cols != other.cols) {
// 抛出异常
throw invalid_argument("Matrices must have the same dimensions.");
}
Matrix res(rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
res.mat[i][j] = mat[i][j] + other.mat[i][j];
}
}
return res;
}
// 乘法
Matrix operator*(const Matrix& other) const {
if (cols != other.rows) {
// 抛出异常
throw invalid_argument("The number of columns in the first matrix must be equal to the number of rows in the second matrix.");
}
Matrix res(rows, other.cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < other.cols; ++j) {
for (int k = 0; k < cols; ++k) {
res.mat[i][j] += mat[i][k] * other.mat[k][j];
}
}
}
return res;
}
};
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)