矩阵转置c++构造函数
时间: 2023-07-01 16:11:21 浏览: 70
矩阵转置的C++构造函数可以这样写:
```c++
class Matrix {
private:
int rows;
int cols;
int **data;
public:
Matrix(int r, int c) {
rows = r;
cols = c;
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
}
}
Matrix(const Matrix& other) {
rows = other.rows;
cols = other.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] = other.data[i][j];
}
}
}
~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}
void transpose() {
int **temp = new int*[cols];
for (int i = 0; i < cols; i++) {
temp[i] = new int[rows];
for (int j = 0; j < rows; j++) {
temp[i][j] = data[j][i];
}
}
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
data = temp;
int tempSize = rows;
rows = cols;
cols = tempSize;
}
};
```
这个构造函数实现了矩阵的转置操作。其中,构造函数 `Matrix(int r, int c)` 创建一个 r 行 c 列的矩阵,并初始化为 0。拷贝构造函数 `Matrix(const Matrix& other)` 创建了一个与另一个矩阵相同大小的矩阵,并将数据拷贝到新矩阵中。析构函数 `~Matrix()` 释放了动态分配的内存。函数 `transpose()` 将矩阵转置,并更新矩阵的大小和数据。
阅读全文