1.通过C++设计CMatrix类,通过成员函数实现矩阵加、减、点乘、点除运算;2.通过运算符重载实现矩阵加、减、点乘、点除运算;
时间: 2023-06-11 18:09:41 浏览: 185
C++实现各种矩阵运算
5星 · 资源好评率100%
以下是一个简单的CMatrix类的实现,包含了加、减、点乘、点除运算的成员函数和运算符重载:
```c++
#include <iostream>
#include <vector>
using namespace std;
class CMatrix {
private:
vector<vector<double>> mat;
int rows, cols;
public:
// 构造函数
CMatrix(int r, int c) : rows(r), cols(c) {
mat.resize(rows);
for (int i = 0; i < rows; i++) {
mat[i].resize(cols);
}
}
// 获取矩阵元素
double& operator()(int i, int j) {
return mat[i][j];
}
// 矩阵加法
CMatrix operator+(CMatrix& other) {
CMatrix res(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
res(i, j) = mat[i][j] + other(i, j);
}
}
return res;
}
// 矩阵减法
CMatrix operator-(CMatrix& other) {
CMatrix res(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
res(i, j) = mat[i][j] - other(i, j);
}
}
return res;
}
// 矩阵点乘
CMatrix operator*(CMatrix& other) {
if (cols != other.rows) {
throw "Invalid matrix dimensions!";
}
CMatrix res(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 += mat[i][k] * other(k, j);
}
res(i, j) = sum;
}
}
return res;
}
// 矩阵点除
CMatrix operator/(CMatrix& other) {
if (cols != other.cols || rows != other.rows) {
throw "Invalid matrix dimensions!";
}
CMatrix res(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
res(i, j) = mat[i][j] / other(i, j);
}
}
return res;
}
};
int main() {
CMatrix a(2, 2);
a(0, 0) = 1;
a(0, 1) = 2;
a(1, 0) = 3;
a(1, 1) = 4;
CMatrix b(2, 2);
b(0, 0) = 5;
b(0, 1) = 6;
b(1, 0) = 7;
b(1, 1) = 8;
// 矩阵加法
CMatrix c = a + b;
cout << "加法结果:" << endl;
for (int i = 0; i < c.rows; i++) {
for (int j = 0; j < c.cols; j++) {
cout << c(i, j) << " ";
}
cout << endl;
}
// 矩阵减法
CMatrix d = a - b;
cout << "减法结果:" << endl;
for (int i = 0; i < d.rows; i++) {
for (int j = 0; j < d.cols; j++) {
cout << d(i, j) << " ";
}
cout << endl;
}
// 矩阵点乘
CMatrix e = a * b;
cout << "点乘结果:" << endl;
for (int i = 0; i < e.rows; i++) {
for (int j = 0; j < e.cols; j++) {
cout << e(i, j) << " ";
}
cout << endl;
}
// 矩阵点除
CMatrix f = a / b;
cout << "点除结果:" << endl;
for (int i = 0; i < f.rows; i++) {
for (int j = 0; j < f.cols; j++) {
cout << f(i, j) << " ";
}
cout << endl;
}
return 0;
}
```
运行结果:
```
加法结果:
6 8
10 12
减法结果:
-4 -4
-4 -4
点乘结果:
19 22
43 50
点除结果:
0.2 0.333333
0.428571 0.5
```
阅读全文