Information Technology Reference
In-Depth Information
Restrictions on Operator Overloading
Not all operators can be overloaded, and there are restrictions on the types of overloading that
can be done. The important things you should know about the restrictions on operator over-
loading are described later in the section.
Only the following operators can be overloaded. Prominently missing from the list is the
assignment operator.
Overloadable unary operators : + - ! ~ ++ -- true false
Overloadable binary operators : + - * / % & | ^ << >> == != >
< >= <=
The increment and decrement operators are overloadable. But unlike the predefined ver-
sions, there is no distinction between the pre- and post- usage of the overloaded operator.
You cannot do the following things with operator overloading:
￿
Create a new operator
￿
Change the syntax of an operator
￿
Redefine how an operator works on the predefined types
￿
Change the precedence or associativity of an operator
Note Your overloaded operators should conform to the intuitive meanings of the operators.
Example of Operator Overloading
The following example shows the overloads of three operators for class LimitedInt : negation,
subtraction, and addition.
class LimitedInt {
const int MaxValue = 100;
const int MinValue = 0;
public static LimitedInt operator -(LimitedInt x)
{
// In this strange class, negating a value just sets its value to 0.
LimitedInt li = new LimitedInt();
li.TheValue = 0;
return li;
}
public static LimitedInt operator -(LimitedInt x, LimitedInt y)
{
LimitedInt li = new LimitedInt();
Search WWH ::




Custom Search