//error class class BadOccur ...{ public: BadOccur(int nErrorNum) ...{ ErrorNum = nErrorNum; } void BadOccurPrint() ...{ cout << ErrorNum <<" error occurs!"<< endl; } private: int ErrorNum; }; //matrix class class CMatrix ...{ public: CMatrix(int Row =0, int Col =0) ...{ if ( Row <0|| Col <0) ...{ throw BadOccur(2); } else ...{ nRows = Row; nCols = Col; pValueArray =newint [Row * Col]; } } intoperator()(int Row, int Col) const //get the element from the position you have given ...{ if ( Row <1|| Row > nRows || Col <1|| Col > nCols) ...{ throw BadOccur(1);//cause error 1 } return pValueArray[(Row -1) * nCols + Col -1]; } int& SetData(int i, int j)//abstract the position for you to set data ...{ return pValueArray[(i -1)* nCols + j -1]; } int nRows; int nCols; int* pValueArray; }; /**//* * Function Name :MultiplyMatrix * function :multiply two matrices * detail :none * author :weixiong * time :2007-2-1 * return type :bool * return description : true two matrices has multiplied * false two matrices can't be multiplied * function parameters :CMatrix& MatrixA multiply matrix A and B * CMatrix& MatrixB * */ bool MultiplyMatrix(CMatrix& MatrixA, CMatrix& MatrixB, CMatrix& ResultMatrix) ...{ if (MatrixA.nCols != MatrixB.nRows) ...{ returnfalse; } else ...{ int Sum =0; for (int Row =1; Row <= MatrixA.nRows; Row++) ...{ for (int Col =1; Col <= MatrixB.nCols; Col++) ...{ for (int i =1; i <= MatrixA.nCols; i++) ...{ Sum = Sum + MatrixA(Row, i) * MatrixB(i, Col); } ResultMatrix.pValueArray[(Row -1) * MatrixB.nCols + Col -1] = Sum; } } returntrue; } } int main() ...{ try ...{ //CMatrix ErrorMatrix(-1, 0);//example of cause error 2 int Row1 =0; int Col1 =0; cout <<"Please enter the row and col for the first matrix."<< endl; cin >> Row1 >> Col1; int Num =1; CMatrix MatrixA(Row1, Col1); for (int i =1; i <= Row1; i++) ...{ for (int j =1; j <= Col1; j++) ...{ MatrixA.SetData(i, j) = Num++; } } //int a = MatrixA(0, 2);//example of cause error 1 int Row2 =0; int Col2 =0; cout <<"Please enter the row and col for the second matrix."<< endl; cin >> Row2 >> Col2; Num =1; CMatrix MatrixB(Row2, Col2); for (int i =1; i <= Row2; i++) ...{ for (int j =1; j <= Col2; j++) ...{ MatrixB.SetData(i, j) = Num++; } } CMatrix ResultMatrix(Row1, Col2); MultiplyMatrix(MatrixA, MatrixB, ResultMatrix); getchar(); } catch(BadOccur m) ...{ m.BadOccurPrint(); } }