使用c++编写一个矩阵类
时间: 2023-08-14 13:04:56 浏览: 145
好的,下面是一个简单的矩阵类的实现,包括矩阵的加、减、乘、转置等基本操作。
```cpp
#include <iostream>
#include <vector>
class Matrix {
public:
Matrix(int rows, int cols) : rows_(rows), cols_(cols) {
data_ = std::vector<std::vector<double>>(rows_, std::vector<double>(cols_, 0));
}
Matrix(const Matrix& other) : rows_(other.rows_), cols_(other.cols_) {
data_ = other.data_;
}
Matrix operator+(const Matrix& other) const {
if (rows_ != other.rows_ || cols_ != other.cols_) {
throw std::invalid_argument("Matrix dimensions do not match.");
}
Matrix result(rows_, cols_);
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < cols_; ++j) {
result.data_[i][j] = data_[i][j] + other.data_[i][j];
}
}
return result;
}
Matrix operator-(const Matrix& other) const {
if (rows_ != other.rows_ || cols_ != other.cols_) {
throw std::invalid_argument("Matrix dimensions do not match.");
}
Matrix result(rows_, cols_);
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < cols_; ++j) {
result.data_[i][j] = data_[i][j] - other.data_[i][j];
}
}
return result;
}
Matrix operator*(const Matrix& other) const {
if (cols_ != other.rows_) {
throw std::invalid_argument("Matrix dimensions do not match.");
}
Matrix result(rows_, other.cols_);
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < other.cols_; ++j) {
double sum = 0;
for (int k = 0; k < cols_; ++k) {
sum += data_[i][k] * other.data_[k][j];
}
result.data_[i][j] = sum;
}
}
return result;
}
Matrix transpose() const {
Matrix result(cols_, rows_);
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < cols_; ++j) {
result.data_[j][i] = data_[i][j];
}
}
return result;
}
void print() const {
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < cols_; ++j) {
std::cout << data_[i][j] << " ";
}
std::cout << std::endl;
}
}
private:
int rows_;
int cols_;
std::vector<std::vector<double>> data_;
};
int main() {
Matrix A(3, 2);
A.print();
std::cout << std::endl;
Matrix B(2, 3);
B.print();
std::cout << std::endl;
Matrix C = A * B;
C.print();
std::cout << std::endl;
Matrix D = C.transpose();
D.print();
std::cout << std::endl;
Matrix E = A + B;
E.print();
std::cout << std::endl;
Matrix F = A - B;
F.print();
std::cout << std::endl;
return 0;
}
```
以上代码定义了一个 Matrix 类,包含了矩阵的加、减、乘、转置等基本操作。在 main 函数中,我们创建了两个矩阵 A 和 B,并分别对它们进行了打印、相乘、转置、相加和相减等操作。
阅读全文