Add inc, dec, ++, and --

This commit is contained in:
Tobias Berger 2021-09-24 12:29:52 +02:00
parent 3946dd2b1c
commit 53d139bc11
3 changed files with 58 additions and 2 deletions

View file

@ -109,6 +109,14 @@ namespace FractionNS {
return *this / n;
}
// Equivalent to ++x and --x, respectively
Fraction& Fraction::inc() {
return ++(*this);
}
Fraction& Fraction::dec() {
return --(*this);
}
bool Fraction::operator==(const int n) const {
return m_denominator == 1
&& m_numerator == n;
@ -346,4 +354,26 @@ namespace FractionNS {
Fraction& Fraction::operator+() const {
return *new Fraction(m_numerator, m_denominator);
}
// Prefix --
Fraction& Fraction::operator--() {
return *new Fraction(*this -= 1);
}
// Postfix --
Fraction& Fraction::operator--(const int) {
auto result = new Fraction(*this);
*this -= 1;
return *result;
}
// Prefix ++
Fraction& Fraction::operator++() {
return *new Fraction(*this += 1);
}
// Postfix ++
Fraction& Fraction::operator++(const int) {
auto result = new Fraction(*this);
*this += 1;
return *result;
}
}

View file

@ -72,6 +72,8 @@ namespace FractionNS {
Fraction& mul(const int) const;
Fraction& div(const Fraction&) const;
Fraction& div(const int) const;
Fraction& inc();
Fraction& dec();
// Binary math operators
Fraction& operator+(const int) const;
@ -109,12 +111,10 @@ namespace FractionNS {
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

@ -31,6 +31,8 @@ private slots:
void test_inverse();
void test_pow();
void test_math_methods();
void test_increment();
void test_decrement();
};
FractionTest::FractionTest() {
@ -500,6 +502,30 @@ void FractionTest::test_math_methods() {
QCOMPARE(f1 / f2, f1.div(f2));
}
void FractionTest::test_increment() {
Fraction f1 = Fraction(2);
const Fraction f2 = f1 + 1;
const Fraction f3 = f2 + 1;
const Fraction f4 = f3 + 1;
QCOMPARE(++f1, f2);
QCOMPARE(f1++, f2);
QCOMPARE(f1, f3);
QCOMPARE(f1.inc(), f4);
}
void FractionTest::test_decrement() {
Fraction f1 = Fraction(2);
const Fraction f2 = f1 - 1;
const Fraction f3 = f2 - 1;
const Fraction f4 = f3 - 1;
QCOMPARE(--f1, f2);
QCOMPARE(f1--, f2);
QCOMPARE(f1, f3);
QCOMPARE(f1.dec(), f4);
}
QTEST_APPLESS_MAIN(FractionTest)
#include "tst_fractiontest.moc"