Wednesday, August 19, 2009

c++: op overloading (:: ?: sizeof .)

Example - Defining + for Point
Using the Point class, adding (does this make sense?) can be defined like this:

//=== Point.h file =============================
Point operator+(Point p) const;

//=== Point.cpp file ===========================
Point Point::operator+(Point p) const {
return Point(x+p.x, y+p.y);
}

//=== myprogram.cpp ============================
Point a(10, 20);
Point b(1, 2);
Point c = a + b;

Define a function which begins with the "operator" keyword

Define a function with the keyword "operator" preceding the operator. There can be whitespace between operator and the operator, but usually they are written together.
Restrictions
Most operators can be redefined, there are restrictions.

* It's not possible to change an operator's precedence.
* It's not possible to create new operators, eg ** which is used in some languages for exponentiation.
* You may not redefine ::, sizeof, ?:, or . (dot).
* Overloading + doesn't overload +=, and similarly for the other extended assignment operators.
* =, [], and -> must be member functions if they are overloaded.
* ++ and -- need special treatment because they are prefix and postfix operators.
* There are special issues with overloading assignment (=) (see Overloading Assignment). Assignment should always be overloaded if an object dynamically allocates memory.

No comments:

Post a Comment