c++定义一个矩阵类代码
时间: 2023-10-21 14:13:48 浏览: 93
Mat_test.rar_矩阵类 C++ mat
下面是一个简单的矩阵类的 C++ 代码示例:
```c++
#include <iostream>
#include <vector>
class Matrix {
private:
int rows, cols;
std::vector<std::vector<int>> data;
public:
Matrix(int r, int c) : rows(r), cols(c), data(std::vector<std::vector<int>>(r, std::vector<int>(c))) {}
int getRows() const {
return rows;
}
int getCols() const {
return cols;
}
int& operator()(int r, int c) {
return data[r][c];
}
const int& operator()(int r, int c) const {
return data[r][c];
}
Matrix operator+(const Matrix& other) const {
if (rows != other.rows || cols != other.cols) {
throw std::invalid_argument("Matrices must have the same dimensions");
}
Matrix result(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result(i, j) = (*this)(i, j) + other(i, j);
}
}
return result;
}
Matrix operator*(const Matrix& other) const {
if (cols != other.rows) {
throw std::invalid_argument("Number of columns in first matrix must equal number of rows in second matrix");
}
Matrix result(rows, other.cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < other.cols; j++) {
int sum = 0;
for (int k = 0; k < cols; k++) {
sum += (*this)(i, k) * other(k, j);
}
result(i, j) = sum;
}
}
return result;
}
friend std::ostream& operator<<(std::ostream& os, const Matrix& matrix) {
for (int i = 0; i < matrix.rows; i++) {
for (int j = 0; j < matrix.cols; j++) {
os << matrix(i, j) << " ";
}
os << std::endl;
}
return os;
}
};
int main() {
Matrix A(2, 3);
A(0, 0) = 1;
A(0, 1) = 2;
A(0, 2) = 3;
A(1, 0) = 4;
A(1, 1) = 5;
A(1, 2) = 6;
Matrix B(3, 2);
B(0, 0) = 7;
B(0, 1) = 8;
B(1, 0) = 9;
B(1, 1) = 10;
B(2, 0) = 11;
B(2, 1) = 12;
Matrix C = A * B;
std::cout << C << std::endl;
return 0;
}
```
这个矩阵类支持矩阵的加法和乘法运算,并可以通过重载 `operator()` 实现类似数组下标的访问方式。在 `main` 函数中,我们定义了两个矩阵 `A` 和 `B`,然后计算它们的乘积 `C`,并将结果输出到控制台上。
阅读全文