写一个矩阵类CMatrix,基本要求如下: ●支持任意大小的矩阵:行数和列数可以动态设置(不用修改代码)●实现拷贝构造函数 o重载操作符*,实现矩阵相乘 ●重载操作符++和一,分别实现矩阵元素同时+1和-1 ●重载操作符=,实现矩阵的赋值 ●在main函数, 中对以上功能进行调用
时间: 2024-03-07 17:46:46 浏览: 47
好的,我可以帮你解答这个问题。以下是实现矩阵类CMatrix的代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
class CMatrix {
public:
CMatrix(int rows, int cols) {
m_rows = rows;
m_cols = cols;
m_data.resize(rows);
for (int i = 0; i < rows; i++) {
m_data[i].resize(cols);
}
}
CMatrix(const CMatrix& other) {
m_rows = other.m_rows;
m_cols = other.m_cols;
m_data = other.m_data;
}
CMatrix operator*(const CMatrix& other) const {
if (m_cols != other.m_rows) {
cerr << "Error: Invalid matrix sizes for multiplication" << endl;
exit(1);
}
CMatrix result(m_rows, other.m_cols);
for (int i = 0; i < m_rows; i++) {
for (int j = 0; j < other.m_cols; j++) {
int sum = 0;
for (int k = 0; k < m_cols; k++) {
sum += m_data[i][k] * other.m_data[k][j];
}
result.m_data[i][j] = sum;
}
}
return result;
}
CMatrix& operator++() {
for (int i = 0; i < m_rows; i++) {
for (int j = 0; j < m_cols; j++) {
m_data[i][j]++;
}
}
return *this;
}
CMatrix operator++(int) {
CMatrix temp(*this);
for (int i = 0; i < m_rows; i++) {
for (int j = 0; j < m_cols; j++) {
m_data[i][j]++;
}
}
return temp;
}
CMatrix& operator--() {
for (int i = 0; i < m_rows; i++) {
for (int j = 0; j < m_cols; j++) {
m_data[i][j]--;
}
}
return *this;
}
CMatrix operator--(int) {
CMatrix temp(*this);
for (int i = 0; i < m_rows; i++) {
for (int j = 0; j < m_cols; j++) {
m_data[i][j]--;
}
}
return temp;
}
CMatrix& operator=(const CMatrix& other) {
m_rows = other.m_rows;
m_cols = other.m_cols;
m_data = other.m_data;
return *this;
}
void print() const {
for (int i = 0; i < m_rows; i++) {
for (int j = 0; j < m_cols; j++) {
cout << m_data[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
private:
int m_rows;
int m_cols;
vector<vector<int>> m_data;
};
int main() {
CMatrix A(2, 3);
A.print();
CMatrix B(3, 4);
B.print();
CMatrix C = A * B;
C.print();
CMatrix D = A++;
A.print();
D.print();
CMatrix E = ++B;
B.print();
E.print();
CMatrix F = A;
F.print();
return 0;
}
```
在上面的代码中,我们定义了一个矩阵类CMatrix,它支持任意大小的矩阵,可以进行矩阵相乘、元素同时+1和-1、赋值等操作。在main函数中,我们对以上功能进行了调用,输出了相应的结果。
注意:这里只是一个简单的实现,可能还有一些细节需要注意。
阅读全文