Operating overloading allows you to pass different variable types to the same function and produce different results. In this article Ben gives us the low-down on operator overloading in C++.
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();