Operator Overloading in C++ - Putting It All Together (Page 6 of 7 ) To demonstrate the Matrix class and its overloaded operators, I've written a sample main() as well as some helper functions that will run the class through its paces: //the functions fill in a matrix with random values--they are type-specific void init_matrix(Matrix<int>& m) { for (int r=0;r<m.GetRows();r++) for (int c=0;c<m.GetCols();c++) m[r][c]=rand()%5+1; }
void init_matrix(Matrix<__int64>& m) { for (int r=0;r<m.GetRows();r++) for (int c=0;c<m.GetCols();c++) m[r][c]=rand()%100000+1; }
void init_matrix(Matrix<float>& m, int precision) { for (int r=0;r<m.GetRows();r++) for (int c=0;c<m.GetCols();c++) { float dec=float(rand()%precision)/precision; m[r][c]=float(rand()%5)+1.0+dec; } }
int _tmain(int argc, _TCHAR* argv[]) { srand((unsigned)time(NULL));
//save/load from file7 Matrix<int> a(5,5); init_matrix(a); a[0][0]=-13; a[1][1]=-13; cout << "Writing to file from Matrix a:" <<endl; cout << a<<endl; ofstream of; of.open("test.txt"); of << a<<endl; of.close(); ifstream iff("test.txt"); if (!iff) { cout << "Error opening file"<<endl; return 1; } Matrix<int> b; cout << "Reading from file into Matrix b:"<<endl; iff >> b; iff.close(); cout <<endl; cout << b<<endl;
cout <<"Press any key to continue..."<<endl; getchar();
//add two floating-point matrices Matrix<float> c(3,2); init_matrix(c,100); cout <<"Matrix c:"<<endl<< c<<endl; Matrix<float> d(3,2); init_matrix(d,100); cout << "Matrix d:"<<endl<<d<<endl; cout << "c+d:"<<endl<<c+d<<endl;
cout <<"Press any key to continue..."<<endl; getchar();
//scale a floating-point matrix Matrix<float> e(10,10); init_matrix(e,1); float scalar=-1.5; cout << "Matrix e:" << endl<<e<<endl; cout << "Scalar: "<<scalar<<endl; cout << "e * scalar:"<<endl<<e*scalar<<endl;
cout <<"Press any key to continue..."<<endl; getchar();
//matrix-product Matrix<__int64> f(3,5); Matrix<__int64> g(5,6); init_matrix(f); init_matrix(g); cout <<"Matrix f:"<<endl<<f<<endl; cout <<"Matrix g:"<<endl<<g<<endl; cout <<"f*g:"<<endl<<f*g<<endl;
cout <<"Press any key to continue..."<<endl; getchar();
return 0; }Next: Conclusion >>
More C++ Articles More By Ben Watson |