Good day! Can you clearly explain about operator overloading?
It is necessary to create a class to represent a simple fraction, which I coped with, but I just can not figure out how to overload operations + , - and so on.

 class SimpleFraction { private: int a, b; public: SimpleFraction(int a1, int a2) { setSimpleFraction(a1, a2 ); if (a2 == 0) throw std::runtime_error("zero division error"); } void setSimpleFraction( int a1, int a2) { a = a1; b = a2; } void getSimpleFraction() { cout << a << "/"<< b ; } }; 

Classes are just starting to learn, so there may be errors

    1 answer 1

    You have here, as they say, the cow did not roll :)
    You should, in general, simplify the fraction after each action - look for the GCD of the numerator and denominator and reduce ...

    Next - why do you need setSimpleFraction ? This can be done simply in the constructor ...

    In a word, it should be like this:

     class SimpleFraction { static int gcd(int m, int n) // Вычисление НОД { while(m && n) if (m < n) n %= m; else m %= n; return (m == 0) ? n : m; } 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"); } // Нас устраивают копирование и присваивание по умолчанию SimpleFraction(const SimpleFraction&) = default; SimpleFraction& operator=(const SimpleFraction&) = default; // Перегрузка оператора вывода в поток friend ostream& operator<<(ostream&out,const SimpleFraction& f) { return out << fa << "/" << fb; } friend SimpleFraction operator +(const SimpleFraction&x, const SimpleFraction&y) { int a = xa*yb + xb*ya; // Числитель int b = xb*yb; // Знаменатель int n = gcd(a,b); // НОД return SimpleFraction(a/n,b/n); } SimpleFraction operator -(const SimpleFraction&y) const { int aa = a*yb - b*ya; // Числитель int bb = b*yb; // Знаменатель int n = gcd(aa,bb); // НОД return SimpleFraction(aa/n,bb/n); } friend SimpleFraction operator *(const SimpleFraction&x, const SimpleFraction&y) { int a = xa*ya; // Числитель int b = xb*yb; // Знаменатель int n = gcd(a,b); // НОД return SimpleFraction(a/n,b/n); } }; int main() { SimpleFraction a(2,3), b(3,5), c(4,9); SimpleFraction x = a+b; cout << x << endl; x = c*b; cout << x << endl; x = ac; cout << x << endl; } 

    operator overloading is just a special kind of function, named operator @ , where @ is the same operator. It can be a member of a class (then its first implicit parameter is *this , it can be free, as in the code above.
    In your case, it is better to have a free one and return a new value of type SimpleFraction - as I did with the + and * operators, but you can also have a class member - see the operator - .

    They simply calculate the new fraction, perform its reduction, and return the new value.

    So enough or something needs to be clarified in more detail?

    • What is missing is the reduction to double. - vp_arth