MFC Programmer's SourceBook : Thinking in C++
Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Syntax

Defining an overloaded operator is like defining a function, but the name of that function is operator@, where @ represents the operator. The number of arguments in the function argument list depends on two factors:

  1. Whether it’s a unary
(one argument) or binary (two argument) operator.

  1. Whether the operator is defined as a global
function (one argument for unary, two for binary) or a member function (zero arguments for unary, one for binary – the object becomes the left-hand argument).

Here’s a small class that shows the syntax for operator overloading:

//: C12:Opover.cpp
// Operator overloading syntax
#include <iostream>
using namespace std;

class Integer {
  int i;
public:
  Integer(int ii) { i = ii; }
  const Integer
  operator+(const Integer& rv) const {
    cout << "operator+" << endl;
    return Integer(i + rv.i);
  }
  Integer&
  operator+=(const Integer& rv){
    cout << "operator+=" << endl;
    i += rv.i;
    return *this;
  }
};

int main() {
  cout << "built-in types:" << endl;
  int i = 1, j = 2, k = 3;
  k += i + j;
  cout << "user-defined types:" << endl;
  Integer I(1), J(2), K(3);
  K += I + J;
} ///:~ 

The two overloaded operators are defined as inline member functions that announce when they are called. The single argument is what appears on the right-hand side of the operator for binary operators. Unary operators have no arguments when defined as member functions. The member function is called for the object on the left-hand side of the operator.

For nonconditional operators (conditionals usually return a Boolean value) you’ll almost always want to return an object or reference of the same type you’re operating on if the two arguments are the same type. If they’re not, the interpretation of what it should produce is up to you. This way complex expressions can be built up:

K += I + J;

The operator+ produces a new Integer (a temporary) that is used as the rv argument for the operator+=. This temporary is destroyed as soon as it is no longer needed.

Contents | Prev | Next


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru