Home > OS >  C OOP divide fractions
C OOP divide fractions

Time:01-26

it is my first post here sorry if it is irrelevant I will delete it.

I started learning C , and I am currently learning OOP with OpenClassrooms.

It asked us at some point to overload some operators on our own to go further...

Here's the thing, I could do it, but I'm not sure to fully understand what happens(And I would like to be able to comment it in order to understand)

here's my code;

ZFraction.h

class Zfraction
{
public:
//Constructor
ZFraction(int num = 0, int denom = 1);

ZFraction& operator/=(ZFraction const& a);
//Other methods and operators
};

ZFraction operator/(ZFraction const& a, ZFraction const& b);
//Other prototypes

ZFraction.cpp

ZFraction& ZFraction::operator/=(const ZFraction& a)
{
    m_denom *= a.m_num;
    m_num *= a.m_denom;

    simplify(); //simplifies the fraction
    return *this;
}

ZFraction operator/(ZFraction const& a, ZFraction const& b)
{
    ZFraction copy(a);
    copy /= b;
    return copy;
}

and main.cpp

ZFraction a(8, 12);     
ZFraction b(7, 4);          
ZFraction c,d,e,f;
////////
f = a/b;

Output : 2/3 / 7/4 = 8/21

I had searched on the internet a lot in order to find a solution, didn't find anything and then end up finding it myself.

So my question is... How does that work exactly ? I'm really unsure... Thank's for answering, let me know if this post is not relevant.

CodePudding user response:

The operator overloads are regular functions with funky names, and they are used through a simple transformation.

a / b is transformed into operator/(a, b), since operator/ is a free function.
copy /= b is transformed into copy.operator/=(b), since operator/= is a member function.

That's all there is to it.
(As far as I know, this transformation idea came from CLU - the most influential programming language nobody's heard of.)

You can even use the functions directly in those forms.
It's not readable, but sometimes it helps when you need to figure out why things aren't evaluated in the way you expect.

  •  Tags:  
  • Related