That really is a poor example because that just works already.
Google operator overloading fractions /complex numbers
As these are the most frequently used.
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
Basically, instead of writing the function addFraction and then calling it a.addFraction(b), where a and b are Fraction objects for example a could be 1/2 and b might be 1/3.
You just write:
a + b and it does the same thing.
As long as you define how you overload the + operator. In your example it is defined here as being:
complex operator+(const complex& c) const {
return complex result(a + c.a, b + c.b);
}
The std::string is a perfect example.
For example, when you concatenate two strings you simply write:
a = "hello";
b = "ugly";
c = a + b;
Now you could have defined a function addString() , which might be called a.addString(b) , but from an onlooker's point of view a + b looks cleaner?
Just think of it as syntax candy.
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
& is pass by reference I believe and the c is just an arbitrary variable name it could be anything you want.
E.g:
complex operator+(const complex& blah) const {
return complex (a + blah.a, b + blah.b);
}
*Edit: If you haven't written classes before or understood the concepts of pass by reference etc, I would do that as a pre-requisite to operator overloading defo!
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439