标签:
#include"Matrix.h" #include<iostream> using namespace std; Matrix::Matrix(int r = 0,int c = 0) { row = r; column = c; } Matrix Matrix::operator+ (const Matrix &m) { Matrix temp(3, 3); if (row != m.row || column != m.column) cout << "这两个矩阵不能相加" << endl; else { for (int i = 0; i < m.row; i++) for (int j = 0; j < m.column; j++) { temp.M[i][j] = M[i][j] + m.M[i][j]; } } return temp; } Matrix Matrix::operator- (const Matrix &m) { Matrix temp(3, 3); if (row != m.row || column != m.column) cout << "这两个矩阵不能相减" << endl; else { for (int i = 0; i < m.row; i++) for (int j = 0; j < m.column; j++) { temp.M[i][j] = M[i][j] - m.M[i][j]; } } return temp; } Matrix Matrix::operator* (const Matrix &m) { Matrix temp(3, 3); if (row != m.column || column != m.row) cout << "这两个矩阵不能相乘" << endl; else { for (int i = 0; i < m.row; i++) for (int j = 0; j < m.column; j++) temp.M[i][j] = 0; for (int i = 0; i < m.row; i++) { for (int j = 0; j < m.column; j++) { for (int k = 0; k < m.row; k++) { temp.M[i][j] = temp.M[i][j] + M[i][j] * m.M[k][i]; } } } } return temp; } void Matrix::operator +=(const Matrix &m) { for (int i = 0; i < m.row; i++) for (int j = 0; j < m.column; j++) M[i][j] = M[i][j]+m.M[i][j]; } Matrix& Matrix::operator =(const Matrix &m) { for (int i = 0; i < m.row; i++) for (int j = 0; j < m.column; j++) this->M[i][j] = m.M[i][j]; return *this; } int Matrix::operator ()(int r, int c) { return M[r][c]; } istream& operator >>(istream &is,Matrix &m) { int(*p)[10]; int *q; for (p = m.M; p < m.M + m.row; p++) for (q = *p; q < *p + m.column; q++) is >> *q; return is; } ostream& operator <<(ostream &os, Matrix &m) { int i, j; for (i = 0; i < m.row; i++) { for (j = 0; j < m.column; j++) { os << m.M[i][j]<<" "; } os << endl; } return os; }
#include"Matrix.h" #include<iostream> using namespace std; int main() { Matrix m1(3,3), m2(3, 3), m3(3, 3); cin >> m1; cin >> m2; m3 = m1; cout<<m3<<endl ; m3 =m1*m2; cout << m3 << endl; system("pause"); return 0; } /* 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 */
标签:
原文地址:http://www.cnblogs.com/da-peng/p/5003999.html