
-----------------------------------
wtd
Sun Oct 31, 2004 7:03 pm

[D] Operator Overloading for C++ Programmers
-----------------------------------
Recap

In a #include 

class Name
{
   private:
      std::string first, last;
   public:
      Name(std::string initFirst, std::string initLast)
      : first(initFirst), last(initLast)
      { }

      std::string getFirst() const { return first; }
      std::string getLast() const { return last; }
      std::string setFirst(std::string newFirst) { return first = newFirst; }
      std::string setLast(std::string newLast) { return last = newLast; }

      std::string fullName() const { return first + " " + last; }
};

D
class Name
{
   private char[] m_first, m_last;

   public
   {
      this(char[] initFirst, char[] initLast)
      {
         m_first = initFirst;
         m_last  = initLast;
      }

      char[] first() { return m_first; }
      char[] last() { return m_last; }
      char[] first(char[] newFirst) { return m_first = newFirst; }
      char[] last(char[] newLast) { return m_last = newLast; }

      char[] fullName() { return m_first + " " + m_last; }
   }
}

Now, for a different take on the problem

Let's say we want to be able to sort names.  Generally the desired method is to sort first by last name, then by first name.  In order to do this, we need to be able to compare two Name objects.  So, we need to overload the logical comparison operators (, =, ==, !=).

C++
#include 

bool operator==(const Name& fn, const Name& sn)
{
   return fn.last == sn.last && fn.first == sn.first;
}

bool operator!=(const Name& fn, const Name& sn)
{
   return fn.last != sn.last || fn.first != sn.first;
}

bool operator sn.first) return true;
      else return false;
   else if (fn.last > sn.last)
      return true;
   else
      return false;   
}

bool operator>=(const Name& fn, const Name& sn)
{
   return fn == sn || fn > sn;
}

D
import std.string;

int opEquals(Name fn, Name sn)
{
   return fn.last == sn.last && fn.first == sn.first;
}

int opCmp(Name fn, Name sn)
{
   if (this.last == n.last)
      return cmp(this.first, this.last);
   else
      return cmp(this.last, n.last);
}

Edited to get rid of unnecessary and cumbersome inheritance.
