Add method versions of operators

This commit is contained in:
Tobias Berger 2021-09-24 12:07:20 +02:00
parent 2a10c5480a
commit 3946dd2b1c
3 changed files with 61 additions and 0 deletions

View file

@ -84,6 +84,31 @@ namespace FractionNS {
float Fraction::toFloat() const { return float(m_numerator) / m_denominator; }
double Fraction::toDouble() const { return double(m_numerator) / m_denominator; }
Fraction& Fraction::add(const Fraction& other) const {
return *this + other;
}
Fraction& Fraction::add(const int n) const {
return *this + n;
}
Fraction& Fraction::sub(const Fraction& other) const {
return *this - other;
}
Fraction& Fraction::sub(const int n) const {
return *this - n;
}
Fraction& Fraction::mul(const Fraction& other) const {
return *this * other;
}
Fraction& Fraction::mul(const int n) const {
return *this * n;
}
Fraction& Fraction::div(const Fraction& other) const {
return *this / other;
}
Fraction& Fraction::div(const int n) const {
return *this / n;
}
bool Fraction::operator==(const int n) const {
return m_denominator == 1
&& m_numerator == n;

View file

@ -63,6 +63,16 @@ namespace FractionNS {
// <=> would go here
// Method versions of operators
Fraction& add(const Fraction&) const;
Fraction& add(const int) const;
Fraction& sub(const Fraction&) const;
Fraction& sub(const int) const;
Fraction& mul(const Fraction&) const;
Fraction& mul(const int) const;
Fraction& div(const Fraction&) const;
Fraction& div(const int) const;
// Binary math operators
Fraction& operator+(const int) const;
Fraction& operator+(const Fraction&) const;
@ -98,5 +108,13 @@ namespace FractionNS {
// Unary operators
Fraction& operator-() const;
Fraction& operator+() const; // Should return a copy of the Fraction.
/*
Fraction& operator++(); // ++x
Fraction& operator++(const int); // x++
Fraction& operator--(); // --x
Fraction& operator--(const int); // x--
*/
};
}

View file

@ -30,6 +30,7 @@ private slots:
void test_greater_than_or_equal();
void test_inverse();
void test_pow();
void test_math_methods();
};
FractionTest::FractionTest() {
@ -482,6 +483,23 @@ void FractionTest::test_pow() {
QVERIFY(threw_not_real_error);
}
void FractionTest::test_math_methods() {
const Fraction f1 = Fraction(9, 7);
const Fraction f2 = Fraction(3, 1);
QCOMPARE(f1 + 3, f1.add(3));
QCOMPARE(f1 + f2, f1.add(f2));
QCOMPARE(f1 - 3, f1.sub(3));
QCOMPARE(f1 - f2, f1.sub(f2));
QCOMPARE(f1 * 3, f1.mul(3));
QCOMPARE(f1 * f2, f1.mul(f2));
QCOMPARE(f1 / 3, f1.div(3));
QCOMPARE(f1 / f2, f1.div(f2));
}
QTEST_APPLESS_MAIN(FractionTest)
#include "tst_fractiontest.moc"