使用类与对象运算符重载实现矩阵类类型加减乘除
时间: 2024-02-03 22:02:03 浏览: 84
C++实现矩阵类
好的,这是一个关于矩阵类类型加减乘除的示例代码,使用运算符重载实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
public:
Matrix(int rows, int cols) {
this->rows = rows;
this->cols = cols;
data = vector<vector<double>>(rows, vector<double>(cols, 0));
}
Matrix operator+(const Matrix& m) const {
if (rows != m.rows || cols != m.cols) {
throw invalid_argument("Cannot add matrices of different sizes");
}
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] + m.data[i][j];
}
}
return result;
}
Matrix operator-(const Matrix& m) const {
if (rows != m.rows || cols != m.cols) {
throw invalid_argument("Cannot subtract matrices of different sizes");
}
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] - m.data[i][j];
}
}
return result;
}
Matrix operator*(const Matrix& m) const {
if (cols != m.rows) {
throw invalid_argument("Cannot multiply matrices of incompatible sizes");
}
Matrix result(rows, m.cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < m.cols; j++) {
double sum = 0;
for (int k = 0; k < cols; k++) {
sum += data[i][k] * m.data[k][j];
}
result.data[i][j] = sum;
}
}
return result;
}
Matrix operator/(double scalar) const {
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] / scalar;
}
}
return result;
}
friend ostream& operator<<(ostream& os, const Matrix& m) {
for (int i = 0; i < m.rows; i++) {
for (int j = 0; j < m.cols; j++) {
os << m.data[i][j] << " ";
}
os << endl;
}
return os;
}
private:
int rows;
int cols;
vector<vector<double>> data;
};
int main() {
Matrix a(2, 3);
a = {{1, 2, 3},
{4, 5, 6}};
Matrix b(3, 2);
b = {{7, 8},
{9, 10},
{11, 12}};
Matrix c = a * b;
cout << c << endl;
Matrix d = a + a;
cout << d << endl;
Matrix e = a - a;
cout << e << endl;
Matrix f = a / 2;
cout << f << endl;
return 0;
}
```
这个示例代码包含了矩阵的加减乘除四个运算符重载,以及一个友元函数输出矩阵。你可以在这个示例代码的基础上,自己实现一个矩阵类类型。
阅读全文