Name: Anonymous 2012-01-21 3:28
preconditions and postconditions as subtypes?
#include <iostream.h>
#include <cassert>
class Int;
class EvenInt;
class OddInt;
class EvenInt {
EvenInt(int value) : value(value) { assert(value%2 == 0); }
EvenInt& operator!=(const EvenInt& other) { value != other.value; return *this; }
EvenInt& operator==(const EvenInt& other) { value == other.value; return *this; }
EvenInt& operator=(const EvenInt& other) { value = other.value; return *this; }
EvenInt& operator+=(const EvenInt& other) { value += other.value; return *this; }
EvenInt& operator-=(const EvenInt& other) { value -= other.value; return *this; }
EvenInt& operator*=(const EvenInt& other) { value *= other.value; return *this; }
EvenInt& operator+(const EvenInt& other) const { return EvenInt(value + other.value); }
OddInt& operator+(const OddInt& other) const { return OddInt(value + other.value); }
EvenInt& operator-(const EvenInt& other) const { return EvenInt(value - other.value); }
OddInt& operator-(const OddInt& other) const { return OddInt(value - other.value); }
EvenInt& operator*(const EvenInt& other) const { return EvenInt(value * other.value); }
int operator(int)() { return EvenInt.value }; // cast to the super type.
int value;
};
class OddInt{
OddInt(int value) : value(value) { assert(value%2 == 1); }
OddInt& operator!=(const OddInt& other) { value != other.value; return *this; }
OddInt& operator==(const OddInt& other) { value == other.value; return *this; }
OddInt& operator=(const OddInt& other) { value = other.value; return *this; }
OddInt& operator+=(const EvenInt& other) { value += other.value; return *this; }
OddInt& operator-=(const OddInt& other) { value -= other.value; return *this; }
OddInt& operator*=(const OddInt& other) { value *= other.value; return *this; }
OddInt& operator+(const EvenInt& other) { return OddInt(value + other.value); }
OddInt& operator-(const OddInt& other) { return OddInt(value - other.value); }
OddInt& operator*(const OddInt& other) { return OddInt(value * other.value); }
int operator(int)() { return OddInt.value }; // cast to the super type.
int value;
};
class NonZeroEvenInt : public EvenInt {
NonZeroEventInt(int value) : EvenInt(value) { assert(value != 0); }
OddInt divideByTwo() const { return OddInt(value/2); }
};