3 Operator overloading

Operators, such as ++, =, <= and etc., can be overloaded in C++. This means that you can redefine what an operator means for a particular type. For example, you can define the following operator for a user defined class:

class X
{
    int i,j;
  // ...
  public:
    int getI(void); // get the value of i
    int getJ(void); // get the value of j
};
  
bool operator== (X a, X b)
{
  return (a.getI() == b.getI()) && (a.getJ() == b.getJ());
}

With these definitions, we can use the overloaded operator as follows:

{
  X mine, yours;

  // ...
  if (mine == yours)
  {
    // ...
  }
  // ...
}

The condition mine == yours is easier to read compared to something like X_equal(mine, yours).



Copyright © 2006-09-12 by Tak Auyeung