1

I make a fraction class, but I want to assign its value to another fraction, usually, I have to do this:

fraction a;
a.setNumerator=(1);
a.setDenominator(2);
b=a; //b is already intialized above

This is long so I made a temporary function like this:

fraction construct (int a, int b)
{
    fraction r;
    if (b!=0)
    r.denominator=b;
    r.numerator=a;
    return r;
}

But I think it's not a good way to do this so how can I construct objects other than this way? The solution I tried: Overload operator = with float type then I can do something like this

a=1/2;

It works well with this case but with a recursive fraction (i.e 1/3), it will just give me a big approximated fraction(16666667/50000000). My float to fraction function:

fraction (float a)
{
    int pow=1;
    while (a*pow!=round(a*pow))
    {
        pow *=10;
    }
    fraction b((int)(a*pow),pow);
    b.simplify();
    numerator=b.numerator;
    denominator=b.denominator;
}
KhiemGOM
  • 69
  • 8
  • 2
    You just write another constructor for you class. That topic is covered in any C++ tutorial. – Ulrich Eckhardt Aug 12 '21 at 05:59
  • In addition to the constructor, you may want to also have a `set(int numerator, int denominator)` member function, that sets both fields at the same time. You may also want to look at the gmp library which provides a class for fractions and all operations on them. – Daniel Junglas Aug 12 '21 at 06:04

1 Answers1

2

The answer is in your own question:

how can I construct objects other than this way?

Write another constructor for fraction which takes 2 ints as input, eg:

fraction (int n, int d) :
    numerator(n), denominator(d)
{
}

Then you can do things like this:

fraction a(1, 2);
b = a;
b = fraction(1, 2);

etc

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    `b = {1, 2};` also becomes possible. – HolyBlackCat Aug 12 '21 at 07:22
  • I don't often use a constructer like this, what is this constructor called? – KhiemGOM Aug 12 '21 at 08:44
  • @KhiemGOM It is just a constructor, like any other (though, in this case, I guess you can call it a [converting constructor](https://en.cppreference.com/w/cpp/language/converting_constructor)). Constructors can be overloaded with different parameter lists. You were already doing that with your `float` constructor (which incidently is creating a temporary `fraction` object using a `fraction(int,int)` constructor). – Remy Lebeau Aug 12 '21 at 17:23