Search code examples
c++operator-overloadingfractions

fraction operator overloading


I am new in C++ and I have a problem with operator overloading. I just implemented the functions in header file.I want to add two fractional numbers simplest form to each other.I implemented a gcd for simplification and implemented operator + for addinf the together bu I got an error for the part in operator+.Error is in fraction add(f1.getNum1()) f1 is highligted : "no instance of construction (fraction::fraction) matching the argumentlist, types are(int,int)" Here is the code:

a& operator+=(const a& f1,const a& f2){
    a add(f1.getNum1()*f2.getDen2()+f2.getNum2()*f1.getDen1(),f1.getDen1()*f2.getDen2());
    return add;
}

#endif

I have another problem in the main.cpp codeno operator "<<" matches these operands operand .I initiliazee the constructor.Now ı want to add to fractional numbers.But I get a n error for cout "<<" in the left side of result : result=fractional1+fractional2; cout << num1 <<"/"<< den1 <<"+"<<num2<<"/"<< den2 <<" = "<<result <<endl;


Solution

  • In your operator+=, you declare a fraction:

    fraction add(f1.getNum1()*f2.getDen2()+f2.getNum2()*f1.getDen1(),f1.getDen1()*f2.getDen2());
    

    This is of the form:

    fraction a(int1, int2);
    

    But you have not defined any constructor for fraction that takes two int arguments. The compiler tells you (correctly) that it doesn't know what you mean.