Thursday, 25 April 2013

Operators as Member Functions

It is possible to define operators for classes. These operators can be infix binary operators
or unary operators. It is only possible to define operators that use an existing C++ operator
symbol, and the precedence of the symbol cannot be changed. There are some operators
that cannot be defined, these are:
. .* :: ?: sizeof # ##
Unary operators are defined as a member function taking no parameters, binary operators
are defined as member functions that take one parameter—the object on the right hand side
of the operator.
When defining an assignment operator (operator=) always declare it to take a reference
to the object on the right hand side of the assignment operator and return a reference to the
object on the left of the operator; this will permit assignments to be chained (a = b = c;).
Also declare the parameter (the object on the right of the operator) to be const to prevent
accidental modification and also to permit const objects to be used on the right hand side
of the assignment operator.
class string {
char *str;
public:
string& operator= (const string& rhs)
{
// delete the current string
delete [] str;
// allocate enough room for the new one
str = new char [ strlen(rhs.str) + 1 ];
// copy in the string
strcpy(str, rhs.str);
return *this; // see 2.2.12
}
};

No comments:

Post a Comment