Operator overloading allows you to extend the functionality of the operators. For example if you do:
Code:
int a = 5;
cout << a;
It will print out '5';
But if you do
Code:
int a [] = {1, 2, 3};
cout << a;
expecting it to print out your three numbers, you will be disappointed as it won't work like that. Now we can overload the stream operator '<<' to accept an array and print out the elements for you as follows:
Code:
#include <iostream.h>
#include <stdlib.h>
#define ELEMENTS 3
void operator << (ostream &out, int a[])
{
for ( int i = 0; i < ELEMENTS; i++)
{
out << a[i] << " ";
}
}
int main()
{
int x[] = {1, 2, 3};
cout << x;
return 0;
}
Is that any clearer?