C++写一个矩阵类cMatrix,基本要求如下: 实现构造、拷贝构造与析构函数 支持任意大小的矩阵:行数和列数可以动态设置(不用修改代码)重载操作符*,实现矩阵相乘 重载操作符=,实现矩阵赋值 重载操作符++和--,分别实现矩阵元素同时+1和-1在main函数中对以上功能进行调用
时间: 2024-03-07 14:47:17 浏览: 79
C++代码的矩阵类,主要包括一些很基本的操作
好的,以下是实现了您要求的基本要求的cMatrix类的代码:
```
#include <iostream>
#include <cassert>
using namespace std;
class cMatrix {
public:
// 构造函数
cMatrix(int numRows, int numCols) : numRows_(numRows), numCols_(numCols) {
data_ = new double*[numRows_];
for (int i = 0; i < numRows_; ++i) {
data_[i] = new double[numCols_];
}
}
// 拷贝构造函数
cMatrix(const cMatrix& other) : numRows_(other.numRows_), numCols_(other.numCols_) {
data_ = new double*[numRows_];
for (int i = 0; i < numRows_; ++i) {
data_[i] = new double[numCols_];
for (int j = 0; j < numCols_; ++j) {
data_[i][j] = other.data_[i][j];
}
}
}
// 析构函数
~cMatrix() {
for (int i = 0; i < numRows_; ++i) {
delete[] data_[i];
}
delete[] data_;
}
// 支持任意大小的矩阵,行数和列数可以动态设置
void resize(int numRows, int numCols) {
double** newData = new double*[numRows];
for (int i = 0; i < numRows; ++i) {
newData[i] = new double[numCols];
for (int j = 0; j < numCols; ++j) {
newData[i][j] = 0;
}
}
for (int i = 0; i < numRows_ && i < numRows; ++i) {
for (int j = 0; j < numCols_ && j < numCols; ++j) {
newData[i][j] = data_[i][j];
}
}
for (int i = 0; i < numRows_; ++i) {
delete[] data_[i];
}
delete[] data_;
data_ = newData;
numRows_ = numRows;
numCols_ = numCols;
}
// 重载操作符*
cMatrix operator*(const cMatrix& other) const {
assert(numCols_ == other.numRows_);
cMatrix result(numRows_, other.numCols_);
for (int i = 0; i < result.numRows_; ++i) {
for (int j = 0; j < result.numCols_; ++j) {
for (int k = 0; k < numCols_; ++k) {
result.data_[i][j] += data_[i][k] * other.data_[k][j];
}
}
}
return result;
}
// 重载操作符=
cMatrix& operator=(const cMatrix& other) {
if (this != &other) {
for (int i = 0; i < numRows_; ++i) {
delete[] data_[i];
}
delete[] data_;
numRows_ = other.numRows_;
numCols_ = other.numCols_;
data_ = new double*[numRows_];
for (int i = 0; i < numRows_; ++i) {
data_[i] = new double[numCols_];
for (int j = 0; j < numCols_; ++j) {
data_[i][j] = other.data_[i][j];
}
}
}
return *this;
}
// 重载操作符++
cMatrix operator++() {
for (int i = 0; i < numRows_; ++i) {
for (int j = 0; j < numCols_; ++j) {
data_[i][j] += 1;
}
}
return *this;
}
// 重载操作符--
cMatrix operator--() {
for (int i = 0; i < numRows_; ++i) {
for (int j = 0; j < numCols_; ++j) {
data_[i][j] -= 1;
}
}
return *this;
}
private:
double** data_;
int numRows_;
int numCols_;
};
int main() {
cMatrix A(2, 3);
A = cMatrix(3, 4);
cout << A.operator++().operator++().operator++() << endl;
cout << A.operator--().operator--().operator--() << endl;
return 0;
}
```
在这个示例中,我们实现了cMatrix类,并且支持动态更改行数和列数,同时实现了矩阵相乘、矩阵赋值、矩阵元素同时+1和-1等基本操作。在main函数中,我们创建了一个2x3的矩阵A,并将其赋值为3x4的矩阵。我们将A的所有元素都加1三次,然后输出结果。接着,我们将A的所有元素都减1三次,并再次输出结果。
阅读全文