|
What is Operator Overloading?
Operator overloading is the ability for a language to redefine the way its operators behave
for certain objects. It allows the programmer to extend the language and give it new abilities. Some languages such as
C++, Algol, python and ruby allow operator overloading, and others such as Java deliberately leave it out. Operator overloading
is a controversial subject for some -- anything that you can do with operator overloading, can also be accomplished by
using appropriate functions and method calls. On the other hand, it may make your code easier to read and comprehend.
It also enables the STL library to work elegantly.
As it happens, C++ is a language that has a lot of operators. In the following pages, we will examine how to overload
different operator types. As we will see later on, it is not necessary to overload all operators for a class, just the ones
that we think should be overloaded. Also, C++ has some code in the standard library that reduces the amount of code that
we need to write.
For the purposes of this discussion, we will implement operator overloading on a complex number class that we will create.
Yes, I know that standard C++ already defines a complex class and overloads the operators, but we will reinvent the wheel
here and learn how operator overloading works at the same time. If you don't know what a complex number is, you can find
the concepts in any basic algebra book. For now, suffice it to say that a complex number has a real and an imaginary part.
You may also perform arithmetic and relational operations between complex numbers or between a complex and a real number.
For the purpose of this discussion, we will start with a complex class that is declared like this:
class Complex {
private:
double real, imag;
public:
Complex() { real = imag = 0; }
Complex(double r, double i) { real = r; imag = i; }
double GetReal(void) const { return real; }
double GetImag(void) const { return imag; }
};
|
|