c语言写一个矩阵类cMatrix,基本要求如下:实现构造、拷贝构造与析构函数;支持任意大小的矩阵:行数和列数可以动态设置(不用修改代码)重载操作符*,实现矩阵相乘;重载操作符=,实现矩阵赋值;重载操作符++和--,分别实现矩阵元素同时+1和-1;在main函数中对以上功能进行调用
时间: 2024-03-06 12:52:04 浏览: 99
下面是一个简单的实现:
```c
#include <iostream>
using namespace std;
class cMatrix {
public:
// 构造函数
cMatrix(int n = 0, int m = 0) : rows(n), cols(m) {
data = new int*[rows];
for (int i = 0; i < rows; ++i) {
data[i] = new int[cols];
for (int j = 0; j < cols; ++j) {
data[i][j] = 0;
}
}
}
// 拷贝构造函数
cMatrix(const cMatrix& mat) {
rows = mat.rows;
cols = mat.cols;
data = new int*[rows];
for (int i = 0; i < rows; ++i) {
data[i] = new int[cols];
for (int j = 0; j < cols; ++j) {
data[i][j] = mat.data[i][j];
}
}
}
// 析构函数
~cMatrix() {
for (int i = 0; i < rows; ++i) {
delete[] data[i];
}
delete[] data;
}
// 矩阵相乘
cMatrix operator*(const cMatrix& mat) const {
if (cols != mat.rows) {
throw "The size of two matrices do not match!";
}
cMatrix result(rows, mat.cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < mat.cols; ++j) {
for (int k = 0; k < cols; ++k) {
result.data[i][j] += data[i][k] * mat.data[k][j];
}
}
}
return result;
}
// 矩阵赋值
cMatrix& operator=(const cMatrix& mat) {
if (this != &mat) {
for (int i = 0; i < rows; ++i) {
delete[] data[i];
}
delete[] data;
rows = mat.rows;
cols = mat.cols;
data = new int*[rows];
for (int i = 0; i < rows; ++i) {
data[i] = new int[cols];
for (int j = 0; j < cols; ++j) {
data[i][j] = mat.data[i][j];
}
}
}
return *this;
}
// 矩阵元素同时+1
cMatrix& operator++() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
++data[i][j];
}
}
return *this;
}
// 矩阵元素同时-1
cMatrix& operator--() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
--data[i][j];
}
}
return *this;
}
// 输出矩阵
friend ostream& operator<<(ostream& os, const cMatrix& mat) {
for (int i = 0; i < mat.rows; ++i) {
for (int j = 0; j < mat.cols; ++j) {
os << mat.data[i][j] << " ";
}
os << endl;
}
return os;
}
private:
int rows;
int cols;
int** data;
};
int main() {
cMatrix mat1(2, 3);
mat1 = cMatrix(2, 3);
mat1 = cMatrix(3, 2);
cMatrix mat2(3, 4);
mat2 = cMatrix(4, 3);
cMatrix mat3 = mat1 * mat2;
cout << mat1 << endl;
cout << mat2 << endl;
cout << mat3 << endl;
++mat1;
cout << mat1 << endl;
--mat1;
cout << mat1 << endl;
return 0;
}
```
在这个例子中,我们首先定义了一个`cMatrix`类,并实现了构造、拷贝构造、析构函数以及运算符重载等功能。在`main`函数中,我们创建了两个矩阵`mat1`和`mat2`,并对它们进行赋值和相乘操作,最后输出结果。同时,我们也演示了如何使用运算符重载来实现矩阵元素同时加减一的操作。
阅读全文