c++利用重载实现矩阵加减乘除
时间: 2023-08-02 12:05:45 浏览: 64
可以利用运算符重载来实现矩阵的加减乘除操作。以下是一个简单的实现示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 矩阵类定义
class Matrix {
public:
Matrix(int r, int c) : rows(r), cols(c), data(r, vector<double>(c)) {}
// 矩阵加法运算符重载
Matrix operator+(const Matrix& other) const {
if (this->rows != other.rows || this->cols != other.cols) {
throw runtime_error("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] = this->data[i][j] + other.data[i][j];
}
}
return result;
}
// 矩阵减法运算符重载
Matrix operator-(const Matrix& other) const {
if (this->rows != other.rows || this->cols != other.cols) {
throw runtime_error("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] = this->data[i][j] - other.data[i][j];
}
}
return result;
}
// 矩阵乘法运算符重载
Matrix operator*(const Matrix& other) const {
if (this->cols != other.rows) {
throw runtime_error("Matrix dimensions do not match.");
}
Matrix result(this->rows, other.cols);
for (int i = 0; i < this->rows; ++i) {
for (int j = 0; j < other.cols; ++j) {
double sum = 0;
for (int k = 0; k < this->cols; ++k) {
sum += this->data[i][k] * other.data[k][j];
}
result.data[i][j] = sum;
}
}
return result;
}
// 矩阵除法运算符重载
Matrix operator/(const Matrix& other) const {
if (this->cols != other.rows) {
throw runtime_error("Matrix dimensions do not match.");
}
Matrix inverse = other.inverse(); // 先求逆矩阵
return (*this) * inverse; // 矩阵乘法实现除法
}
// 求逆矩阵
Matrix inverse() const {
if (this->rows != this->cols) {
throw runtime_error("Matrix is not square.");
}
int n = this->rows;
Matrix result(n, n);
// 先做初等变换,将原矩阵变成单位矩阵
for (int i = 0; i < n; ++i) {
result.data[i][i] = 1;
}
for (int i = 0; i < n; ++i) {
double factor = this->data[i][i];
for (int j = 0; j < n; ++j) {
this->data[i][j] /= factor;
result.data[i][j] /= factor;
}
for (int k = 0; k < n; ++k) {
if (k == i) {
continue;
}
double factor = this->data[k][i];
for (int j = 0; j < n; ++j) {
this->data[k][j] -= factor * this->data[i][j];
result.data[k][j] -= factor * result.data[i][j];
}
}
}
return result;
}
private:
int rows, cols; // 矩阵行数和列数
vector<vector<double>> data; // 矩阵数据
};
int main() {
Matrix A(2, 3);
A.data = {{1, 2, 3}, {4, 5, 6}};
Matrix B(3, 2);
B.data = {{7, 8}, {9, 10}, {11, 12}};
Matrix C = A + A;
C = C - A;
Matrix D = A * B;
Matrix E = D / B;
return 0;
}
```
在上面的示例代码中,我们定义了一个 `Matrix` 类来表示矩阵,并实现了矩阵加减乘除四种运算符重载。其中矩阵除法是通过先求逆矩阵再做矩阵乘法实现的。在 `Matrix` 类中还实现了求逆矩阵的函数 `inverse()`,用于求矩阵的逆矩阵。