Define a class RationalNumber with suitable data members and member function.
Overload the different operators participating in the following expression to get the result
class RationalNumber
{
private:
int numerator;
int denominator;
public:
RationalNumber(int num, int denom) : numerator(num), denominator(denom) {}
RationalNumber(int num) : numerator(num), denominator(1) {}
RationalNumber operator+(const RationalNumber& second_number)
{
if (this->denominator == second_number.denominator)
{
return RationalNumber(this->numerator + second_number.numerator, denominator);
}
else
{
return RationalNumber(this->numerator * second_number.denominator + second_number.numerator * this->denominator, this->denominator * second_number.denominator);
}
}
RationalNumber operator-(const RationalNumber& second_number)
{
if (this->denominator == second_number.denominator)
{
return RationalNumber(this->numerator - second_number.numerator, denominator);
}
else
{
return RationalNumber(this->numerator * second_number.denominator - second_number.numerator * this->denominator, this->denominator * second_number.denominator);
}
}
RationalNumber operator*(const RationalNumber& second_number)
{
return RationalNumber(this->numerator * second_number.numerator, this->denominator * second_number.denominator);
}
RationalNumber operator/(const RationalNumber& second_number)
{
return RationalNumber(this->numerator * second_number.denominator, this->denominator * second_number.numerator);
}
int get_numerator()
{
return numerator;
}
int get_denominator()
{
return denominator;
}
void set_numerator(int num)
{
numerator = num;
}
void set_denominator(int denom)
{
denominator = denom;
}
};
Comments
Leave a comment