I'm having trouble figuring out how to overload the +=, -=, *=, and /= for a program that does operations with rational numbers. Could someone please help me out.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
class Rational{
public:
int num;
int den;
bool neg;
Rational(int n, int d); // contructor for rationals
Rational(int n); // contructor for reals
Rational();//default constructor
int get_num();
int get_denom();
int gcd();
void simplify();
bool is_negative();
Rational operator +(Rational);
Rational operator -(Rational);
Rational operator *(Rational);
Rational operator /(Rational);
Rational operator +=(Rational);
// Rational operator -=(Rational);
//Rational operator /=(Rational);
//Rational operator *=(Rational);
//int num, den, real, final_num, numer1, numer2, denom;
};
int main(){
Rational result, a, rat(1,2), rat2(3,2), rat3(6,-3), rat4(-3,-8);
//result.den = a.get_denom();
//result.num = a.get_num();
//result.neg = a.is_negative();
//cout << result.num << "/" << result.den << endl;
//cout << result.neg << endl;
rat += rat2;
cout << rat.num << "/" << rat.den << endl;
}
Rational::Rational(int n, int d)
{
if(n == 0)
{
num = n;
den = 1;
}else
{
num = n;
den = d;
}
}
Rational::Rational(int n)
{
num = n;
den = 1;
}
Rational::Rational()
{
num = 0;
den = 1;
}
int Rational::get_num()
{
simplify();
return abs(num);
}
int Rational::get_denom()
{
simplify();
return abs(den);
}
int Rational::gcd()
{ int a = num;
int b = den;
int temp;
while(b != 0)
{
temp = b;
b = a % b;
a = temp;
}
return a;
}
void Rational::simplify()
{
int gcdNum = gcd();
if(gcdNum != 0)
{
num = num / gcdNum;
den = den / gcdNum;
}
}
bool Rational::is_negative()
{
if(num < 0||den < 0)
neg = true;
else
neg = false;
return neg;
}
Rational Rational:: operator +(Rational ratPassed)
{
Rational ratResult;
ratResult.num = num * ratPassed.den + den * ratPassed.num;
ratResult.den = den * ratPassed.den;
return ratResult;
}
Rational Rational:: operator -(Rational ratPassed)
{
Rational ratResult;
ratResult.num = num * ratPassed.den - den * ratPassed.num;
ratResult.den = den * ratPassed.den;
return ratResult;
}
Rational Rational:: operator *(Rational ratPassed)
{
Rational ratResult;
ratResult.num = num * ratPassed.num;
ratResult.den = den * ratPassed.den;
return ratResult;
}
Rational Rational:: operator /(Rational ratPassed)
{
Rational ratResult;
ratResult.num = num * ratPassed.den;
ratResult.den = den * ratPassed.num;
return ratResult;
}
Rational Rational:: operator +=(Rational ratPassed)
{
Rational ratResult;
ratResult.num = num * ratPassed.den + den * ratPassed.num;
ratResult.den = den * ratPassed.den;
return ratResult;
}
/*Rational Rational::operator *=(Rational lhs, Rational rhs)
{
lhs.num = lhs.num * rhs.num;
lhs.den = lhs.den * lhs.den;
return lhs;
}*/
//Rational operator -=(Rational)
//Rational operator /=(Rational)
//Rational operator *=(Rational)