Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

preconditions and postconditions as subtypes?

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); }
};

Name: Anonymous 2012-01-21 3:31

and this is why operator overloading should never exist.

Name: Anonymous 2012-01-21 3:41

>>2
it has its uses, but it's terribly abused

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List