views:

688

answers:

3

I have the following constructor in my "fraction class"

fraction::fraction(int num, int den=1)
{
     numerator=num;
     denominator=den;
}

I also have a function called lcm() that returns the least common multiple of values given as parameters. I need to overload the "+" operator in the class fraction. The operator "+" is to add two rational values.

Questions:

  1. Write the overloaded "+" operator as a member method of the class.
  2. Write the overloaded "+" operator as a friend function to the class.
  3. One of these gives an advantage over the other. Which one is better? Why is it better?

Any help will be greatly appreciated.

+2  A: 

Standard algorithms. Study. Do you really expect people to do your homework? Google is your friend.

dirkgently
Why not link him to something that is more useful to him advancing on his question than leaving an empty comment?
SD
That's so recursive.
eed3si9n
Well I answered another of his homework assignments 30 seconds back and this pissed me off.
dirkgently
@dirkgently, I understand. However, how do you know it is this guy?
Simucal
All unknowns are equal for me ;) First of all they don't even bother to register. And then, they'd post their homework verbatim. It's so depressing.
dirkgently
+8  A: 

Have a look at: SO: How to define a friend function and how to do operator overloading?

  1. Friends in C++
  2. Operator overloading in C++

Also, while homework is allowed, you'll get better answers if you ask specific questions about what things you are actually confused on.

You aren't going to get a good response if you just list off homework problems and expect us to do them for you.

For example, attempt your homework yourself and if you hit a snag, post a specific question citing your attempt, what isn't working and we'll help tell you why.

Simucal
+3  A: 

Some ideas which are possibly not so easy to find using google, so i will tell you:

The friend, non-member function is better. It will allow conversions on both left and right operand of the + operator. The + operator is symmetric, and the non-member operator function supports this property syntactically by treating each side of the operator the same way.

On another side, you can write that implementing the operator as a non-friend, non-member function is even better, because then you have one function less that has access to implementation details of the class. But as this is not what was asked for, i would put it as a side-node, if at all.

I will leave writing the code to you, though. Just the general idea is that you write the function somewhat like this:

fraction operator+(fraction const& left, fraction const& right) {
    // put your code here...
}

As to how you declare that function as friend - i think there are many sites on the internet explaining that in great detail (have a look into the FAQ Simucal linked to. It's really good). I wish you good luck :)

Johannes Schaub - litb