diff --git a/fraction.cpp b/fraction.cpp index 5279bba..7b14cb4 100644 --- a/fraction.cpp +++ b/fraction.cpp @@ -183,4 +183,23 @@ namespace FractionNS { reduce(); return *this; } + + Fraction& Fraction::operator/(const int n) const { + return *new Fraction(m_numerator, m_denominator * n); + } + Fraction& Fraction::operator/(const Fraction& other) const { + return *new Fraction(m_numerator * other.getDenominator(), m_denominator * other.getNumerator()); + } + + Fraction& Fraction::operator/=(const int n) { + m_denominator *= n; + reduce(); + return *this; + } + Fraction& Fraction::operator/=(const Fraction& other) { + m_numerator *= other.getDenominator(); + m_denominator *= other.getNumerator(); + reduce(); + return *this; + } } diff --git a/fraction.hpp b/fraction.hpp index 2dee8c4..93d6e05 100644 --- a/fraction.hpp +++ b/fraction.hpp @@ -49,5 +49,11 @@ namespace FractionNS { Fraction& operator*=(const int); Fraction& operator*=(const Fraction&); + + Fraction& operator/(const int) const; + Fraction& operator/(const Fraction&) const; + + Fraction& operator/=(const int); + Fraction& operator/=(const Fraction&); }; } diff --git a/tst_fractiontest.cpp b/tst_fractiontest.cpp index ab977a8..119a4b6 100644 --- a/tst_fractiontest.cpp +++ b/tst_fractiontest.cpp @@ -21,6 +21,7 @@ private slots: void test_inequivalence(); void test_substraction(); void test_multiplication(); + void test_division(); }; FractionTest::FractionTest() {}; @@ -196,6 +197,19 @@ void FractionTest::test_multiplication() QCOMPARE(f1 * Fraction(2, 3), 4); } +void FractionTest::test_division() { + Fraction f1 = Fraction(1, 1); + const Fraction f2 = Fraction(1, 2); + QCOMPARE(f1 / 2, f2); + + f1 /= 2; + qDebug() << f1.display(); + QCOMPARE(f1, 0.5); + QCOMPARE(f1 / 2, 0.25); + + QCOMPARE((f1 / 2) / Fraction(2, 3), Fraction(3, 8)); +} + QTEST_APPLESS_MAIN(FractionTest) #include "tst_fractiontest.moc"