an
example of operator overloading:
Say you want to add 2 complex numbers (in mathematics, a complex number is a number with 2 parts, a real and an imaginary, written like (1,2i) with the first number being the real number and the second being the imaginary.) Say you want to add 2 of these complex numbers (added as ((xr + yr), (xi + yi)i).) In C, you would probably devise a structure something like this to hold the data:
struct complex
{
double real;
double imag;
};
And you would add these two structs something like this, needing to devise a function that adds complex numbers and returns the sum:
added = addComplex(a, b);
But wouldn't it make more sense to be able to do it like this?
added = a + b;
Well, with operator overloading you can. Devise your class like this:
class complex
{
private:
double real;
double imag;
public:
complex();
~complex();
complex operator+(complex &);
};
You will, of course, need to define your class constructor (complex()) and your destructor (~complex()). Then, you tell the compiler how to overload the addition operator to add two of these classes together:
compex complex::operator+(comlex & cnum)
{
complex temp; // new temporary class
temp.real = real + cnum.real;
temp.imag = imag + cnum.imag;
return temp;
}
This enables the compiler to know how to add two of the same classes together. You can use any standard operator for C++ overloading.
Another cool feature of operator overloading is the ability to kind-of re-write the istream and ostream classes (those are the classes in C++ that deal with input/output, roughly equivalent to stdio.h in C) to be able to tell cout (basically printf()) to print the class merely by passing the class to the ostream.
I am not very good at explaining things, but I hope I have demonstrated to you the basics of C++ operator overloading.