-3
Class fraction
{
public:
      fraction operator+ (const fraction& fr) const;
private:
      int num; //numerator 
      int den; //denominator
};

I wanted to overlaod the operator+ so that it perfoms the multiplication of an integer constant (calling object) and a fraction.

fraction fraction::operator+ (const fraction& fr) const
{
    fraction result;

    result.num = fr.num + fr.den * (*this);
    //error message says invalid operands to binary exprssion ('int' and 'constant fraction')
    result.den = fr.den;

    simplified_fr(result); // a helper function to simplify the resulted fraction 
    return result;
}

It seems that the problem is about the type of calling object. I intended to make it a constant integer but the computer thought it was a 'const fraction'. Can someone please advise me why this happened and how can I fix it? Thank you in advance!!!

Phyllis Qu
  • 27
  • 5
  • This `new_fr.num = fr.num * (*this);` is pointless, you want to do some `int` arithmetics in the implementation instead of `fraction`; `result.den = fr.den;` this is mathematically wrong. – llllllllll Feb 24 '18 at 22:19
  • Relevant: https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading?rq=1 – chris Feb 24 '18 at 22:25
  • Read this: [MCVE] – Jive Dadson Feb 24 '18 at 22:34
  • `this->num` instead of `(*this)`? Might I also suggest to dive into `std::ratio`? – Vivick Feb 24 '18 at 22:43
  • hmm, num is a member of the class object. But the calling object 'this' pointed to is intended to be an integer. So, I didn't quite get how 'this->num' would work? – Phyllis Qu Feb 24 '18 at 22:51
  • Don't insist on using a member-function, and your problems disappear. – Deduplicator Feb 24 '18 at 23:05

1 Answers1

0

I assume you would like to do achieve something like this:

fraction fract;
fraction fract2 = 2 + fract;

The answer is that you cannot overload member method operator+ for non-class objects. BUT you can define/overload global operator+ function:

fraction operator+(int num, const fraction& rFrac)
{
//your implementation
}

You will probably need access to private members of fraction class. That can be acomplished by making operator+ a friend:

class fraction
{
    //...
    friend fraction operator+(int num, const fraction& rFrac);
    //...
}
Quimby
  • 17,735
  • 4
  • 35
  • 55
  • Btw, could a friend function directly use the helper methods of the class? – Phyllis Qu Feb 24 '18 at 23:32
  • @PhyllisQu Depends, friend means that the function can see private stuff of the class, nothing more. So operator+ can use private static methods and static variables. It can also call private member methods on an instance of the class. But it does not have implicit `this` pointer, because it is not called on an instance. – Quimby Feb 24 '18 at 23:59
  • I see! Thank You!! – Phyllis Qu Feb 25 '18 at 00:28