diff --git a/Matrix/main.cpp b/Matrix/main.cpp index 5d7a01f..a8d45de 100644 --- a/Matrix/main.cpp +++ b/Matrix/main.cpp @@ -31,6 +31,44 @@ int main() { int out[] = { 1,2,3,4 }; matrix tmp(2, 2, out); tmp = left * right; - cout << "times: " << endl << tmp << endl; + cout << "times: " << endl << tmp << endl << endl; + + //还是有地方浅拷贝了,调试过程中最好加上引用 + //大概率是拷贝构造函数的问题,如果直接输出非引用,会创建新的对象,这个对象会出问题,比如double delete之类 + cout << "transpose: " << endl << tmp.transpose() << endl; + cout << "transpose left: " << endl << left.transpose() << endl; + cout << "transpose right: " << endl << right.transpose() << endl; return 0; -} \ No newline at end of file +} + +/* +left: +1 2 3 +4 5 6 + +right: +1 2 +3 4 +5 6 + +left(1, 1): 1 +right(2, 1): 3 + +times: +22 28 +49 64 + + +transpose: +22 49 +28 64 + +transpose left: +1 4 +2 5 +3 6 + +transpose right: +1 3 5 +2 4 6 +*/ \ No newline at end of file diff --git a/Matrix/matrix.h b/Matrix/matrix.h index 8012e89..c11271c 100644 --- a/Matrix/matrix.h +++ b/Matrix/matrix.h @@ -22,6 +22,7 @@ public: matrix operator-(const matrix& x) const; matrix operator*(const matrix& x) const; matrix& operator+=(const matrix& x); + matrix& transpose(); template friend std::ostream& operator<<(std::ostream& os, const matrix& x); @@ -53,12 +54,16 @@ matrix::matrix(int rows, int cols, T* x) : rows(rows), cols(cols){ if (rows < 0 || cols < 0) { throw std::out_of_range("Matrix subscript out of range"); } - + int sum = rows * cols; element = new T[sum]; - for (int i = 0; i < sum; i++) { - element[i] = x[i]; + if (x) { + for (int i = 0; i < sum; i++) element[i] = x[i]; } + else { + for (int i = 0; i < sum; i++) element[i] = T(); + } + } template @@ -146,3 +151,18 @@ std::ostream& operator<<(std::ostream& os, const matrix& x) { } return os; } + +template +matrix& matrix::transpose() { + T* telement = new T[rows * cols]; + for (int i = 1; i <= rows; i++) { + for (int j = 1; j <= cols; j++) { + telement[(j - 1) * rows + i - 1] = (*this)(i, j); + } + } + + delete[] element; + std::swap(rows, cols); + element = telement; + return *this; +}