How to realize Matrix Operation in C++
This article will explain in detail how to implement matrix operation on C++. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
The construction of matrix is realized by C++, and the multiplication and addition of matrix are realized by the overloading of operators. And realize the matrix shape printing, matrix printing.
# include#include#include#includeusing namespace std;class Matrix {public: Matrix (int row, int col); / / constructor Matrix (int row, int col, int num); / / constructor overload ~ Matrix (); / / destructor Matrix (const Matrix& other); / / assignment function Matrix operator* (const Matrix& other) / / Matrix multiplication Matrix operator+ (const Matrix& other); / / Matrix addition Matrix operator- (const Matrix& other); / / Matrix subtraction int * * a = nullptr; / / initialize a common null pointer int row, col; void shape (); / / print matrix shape void Ma_pri () / / print matrix}; int main () {Matrix a (2); / / construct a (2) matrix Matrix b (1); / / construct a (1) matrix a.a [0] [0] = 4; / / initialize matrix a.a [1] [0] = 2; b.a [0] [0] = 3; b.a [0] [1] = 5 A.shape (); / / Matrix shape printing b.shape (); Matrix c = aplimb; / / Matrix multiplication c.shape (); c.Ma_pri (); / / Matrix printing Matrix d (310); d.Ma_pri (); system ("pause"); return 0;} Matrix::Matrix (int row, int col) {this- > row = row This- > col = col; this- > a = new int* [row]; for {a [I] = new intn [this-> col];}} Matrix::Matrix (int row, int col, int num) {this- > row = row; this- > col = col; this- > a = new int* [row]; for (int Irowx +) {a [I] = new intt [this-> col] } for (int I = 0; I
< this->Row;i++) {for (int j = 0; j row; jacks +) {this- > a [I] [j] = num;}} Matrix::~Matrix () {for (int ionome0 / irowtransferi +) {if (a [I]! = nullptr) {delete [] a [I]; a [I] = nullptr }} if (a! = nullptr) {delete [] a; a = nullptr;}} Matrix::Matrix (const Matrix& other) {row = other.row; col = other.col; a = new int* [row]; for (int item0 poliicol! = other.row) {couta [I] [j] + other.a [I] [j];}} return m } Matrix Matrix::operator- (const Matrix& other) {if (this- > col! = other.col or this- > row! = other.row) {cout col; jacks +) {m.a [I] [j] = this- > a [I] [j]-other.a [I] [j];}} return m;} void Matrix::shape () {cout