定义一个矩阵类 Matrix均为 M 行 N 列通过重载运算符+、-++--==!=来实现矩阵的相加、相减、输出、输入、自增、自减以及相等、不等的判断。
class Matrix{ private: int M, N; int **mat; public: Matrix(int m=0, int n=0){ M = m; N = n; mat = new int *[M]; for(int i=0; i<M; i++){ mat[i] = new int [N]; for(int j=0; j<N; j++){ mat[i][j] = 0; } } } Matrix(const Matrix& other){ M = other.M; N = other.N; mat = new int *[M]; for(int i=0; i<M; i++){ mat[i] = new int [N]; for(int j=0; j<N; j++){ mat[i][j] = other.mat[i][j]; } } } ~Matrix(){ for(int i=0; i<M; i++){ delete [] mat[i]; } delete [] mat; } Matrix& operator=(const Matrix& other){ if(this != &other){ for(int i=0; i<M; i++){ delete [] mat[i]; } delete [] mat; M = other.M; N = other.N; mat = new int *[M]; for(int i=0; i<M; i++){ mat[i] = new int [N]; for(int j=0; j<N; j++){ mat[i][j] = other.mat[i][j]; } } } return *this; } Matrix operator+(const Matrix& other){ Matrix res(M, N); for(int i=0; i<M; i++){ for(int j=0; j<N; j++){ res.mat[i][j] = mat[i][j] + other.mat[i][j]; } } return res; } Matrix operator-(const Matrix& other){ Matrix res(M, N); for(int i=0; i<M; i++){ for(int j=0; j<N; j++){ res.mat[i][j] = mat[i][j] - other.mat[i][j]; } } return res; } friend ostream& operator<<(ostream& os, const Matrix& m){ for(int i=0; i<m.M; i++){ for(int j=0; j<m.N; j++){ os << m.mat[i][j] << " "; } os << endl; } return os; } friend istream& operator>>(istream& is, Matrix& m){ for(int i=0; i<m.M; i++){ for(int j=0; j<m.N; j++){ is >> m.mat[i][j]; } } return is; } Matrix& operator++(){ for(int i=0; i<M; i++){ for(int j=0; j<N; j++){ mat[i][j]++; } } return *this; } Matrix operator++(int){ Matrix res(*this); ++(*this); return res; } Matrix& operator--(){ for(int i=0; i<M; i++){ for(int j=0; j<N; j++){ mat[i][j]--; } } return *this; } Matrix operator--(int){ Matrix res(*this); --(*this); return res; } bool operator==(const Matrix& other){ if(M != other.M || N != other.N){ return false; } for(int i=0; i<M; i++){ for(int j=0; j<N; j++){ if(mat[i][j] != other.mat[i][j]){ return false; } } } return true; } bool operator!=(const Matrix& other){ return !(*this == other); } }
原文地址: https://www.cveoy.top/t/topic/epzE 著作权归作者所有。请勿转载和采集!