by John
Kopp
Welcome to About.com's tutorial on C++ programming. This
lesson covers the topic of operator overloading. Operator
overloading provides a way to define and use operators
such as +, -, *, /, and [] for user defined types such as classes
and enumerations.
By defining operators, the use of a class can be made as
simple and intuitive as the use of intrinsic data types.
Let's develop a "fraction" class to illustrate the use and
utility of operator overloading. First, consider which
operators are normally associated with fractions and should be
included in this class. Operators such as +, -, *, / are
givens. C++ allows any of its built in operators to be
overloaded in a class, but only those that have an intuitive
meaning for a particular class should actually be overloaded.
For instance, although the modulo
operator, %, could be overloaded for our fraction class, its
meaning would be unclear and defining it would only confuse
users of the class. %1/2 has no clear interpretation.
To begin, here is an implementation of the fraction class
with an add method. Note that in order to simplify the
implementation of the add method, I am using the greatest
common denominator of the two fractions rather than the least.
#include <iostream> using namespace
std;
class Fraction
{ public: Fraction(int num
= 0, int den =
1) { this->num
=
num; this->den
=
den; } Fraction
add(const Fraction
&rhs) { Fraction
temp; temp.den
= this->den *
rhs.den; temp.num
= rhs.den * this->num +
this->den
*
rhs.num; return
temp; } void
print() { cout
<< num << "/" << den <<
endl; } private: int
num; int
den; };
int main()
{ Fraction
a(1,2); Fraction
b(1,4); Fraction
c;
a.print(); b.print();
c
=
a.add(b);
c.print();
return
0; }
| Output: 1/2 1/4 6/8
Notice
that a temporary Fraction object was created within the add
method. This was necessary because "add" must return a
Fraction, since its result is assigned to a Fraction. The use
of the add method is somewhat awkward. Rather than a.add(b),
we'd like to be able to write "a + b". This can be done with
operator overloading, as shown on the following page.
Next
page > Simple
Overloaded Operators > Page 1,
2,
3,
4,
5,
6,
|