0

Could you explain me how to correctly multiply the fraction by the number? Tried to overload, but I get compiler error:

binary operator * : the operator accepting the left operand of type of the SimpleFraction is not found

class SimpleFraction 
{
static int findGcd(int a, int b)
{
    while (a&&b)
    {
        if (a > b)
            a %= b;
        else
            b %= a;

    }
    return (a == 0) ? b : a;
}

private:
int a,
    b;
public:
SimpleFraction(int a1 = 0, int a2 = 1) :a(a1), b(a2) 
{
    if (a2 == 0)
        throw std::runtime_error("zero division error");
}

friend ostream& operator<<(ostream&out, const SimpleFraction& f)
{
    return out << f.a << "/" << f.b ;
}

friend istream& operator >> (istream&in, SimpleFraction& f) 
{
    char t;
    return in >> f.a >>t>> f.b;
}

friend SimpleFraction operator *(const SimpleFraction&x, int n) 
{
    int a = x.a *n;
    int gcd = finGcd(a, x.b);
    return SimpleFraction(a / gcd, x.b / gcd);
}
};

I get that error message , when I enter such code

int main()
{
SimpleFraction SFArray1(2, 2);
SimpleFraction r = SFArray1 * 2;
cout << r;
return 0;
}
Rama
  • 3,222
  • 2
  • 11
  • 26
choko
  • 113
  • 5

1 Answers1

0
friend SimpleFraction operator *(const SimpleFraction&x, int n)

You don't need to use the friend keyword here. The operator * should be overloaded as part of the class. Your function signature should look something like this:

SimpleFraction operator *(const SimpleFraction& rightOperand) const {
/* ...implementation which should use values of "this" and rightOperand and return a newly instantiated SimpleFraction*/
    SimpleFraction result(this->a * rightOperand.a, this->b * rightOperand.b);
    return result;
}

Update after OP edit

Looking at your code in main, you would have to do another overload with a int value like so:

SimpleFraction operator *(const int& rightOperand) const {
    SimpleFraction result(this->a * rightOperand.a, this->b); // I'm guessing you take "a" as a numerator  
    return result;
}

Furthermore, in your main() function you use SimpleFraction = operator. So you should implement the operator= function as well as the Copy Constructor as per the Rule of Three.

Community
  • 1
  • 1
Santiago Varela
  • 2,199
  • 16
  • 22