I'm working on a fractions class in C++ and have defined the addition of a frac and an int in the new class, but it requires them to show up in that order: frac + int. Is there a way to overload + in the Int type such that we have a function that accepts a frac and outputs a frac? Or is there a way to reverse the order in the new class?
I already have frac + frac and frac += frac operators defined. The two functions in question are:
frac operator+=(int b)
{
frac c = { n + b*d, d };
return c;
}
frac operator+(int b)
{
frac c = *this;
frac d = { b };
c += d;
return c;
}
something like this:
frac int::operator+=(frac& b)
{
frac c = { this * b.den() + b.num(), b.den() };
return c;
}
But I'm not sure how to actually accomplish this.
Code from question below:
frac &operator+=(frac b)
{
frac c = { n * b.den() + b.num() * d, d * b.den() };
n = c.num();
d = c.den();
return *this;
}
frac operator+(int a, frac b)
{
return frac{ a } += b;
}
Well there's no class int
so you can't do what you suggested but the easy thing is to declare a function like this (inside your class)
friend frac operator+(int a, frac b);
That way this function will be called when the other order is used. Edit: you need to use the friend
specifier because the function isn't in the class, I forgot about that.