Defining Operator Overloading
To define an additional task to an operator, we must specify what it means in relation to the class to which the operator is applied. This is done with the help of a special function, called operator function, which describes the task. The general from of an operator function is:
Returntype class_name :: operator op(art_list)
{
Function body // task defined
}
Where returntype is the type of value returned by the specified operation and op is the operator being overloaded. The op is preceded by the keyword Operator. Operator op is the function name.
Operator functions must be either member function (non-static) or friend functions. A basic difference between them is that a friend function will have only one argument for unary operators and two for binary operators, while a member function has no argument for unary operators and only one binary operator. This is because the object used to invoke the member function is passed implicitly and therefore is available for the member function.
Operator function are declared in the using prototypes as follows.
vector operator + (vector) // vector addition
vector operator - // unary minus
friend vector operator –(vector); // vector addition
friend vector operator – (vector); // unary minus
vector operator – (vector & a); // subtraction
int operator = = (vector) // comparison
friend int operator = =(vector, vector) // comparison
Vector is a data type of class and may represent both magnitude and direction.
The process of overloading involves the following steps:
- First create class that defines the data type that is to be used in the overloading operation.
- Declare the operator function operator op() in the public part of the class. It may be either a member function or a friend function.
- Define the operator function to implement the required operations.
Overloaded operator function can be invoked by expressions such as
op x or x op (x represents operand) for unary operator and
x op y for binary operators.
op x(or x op) would be interpreted as operator op(x)
For friend function. Similarly, the expression x op y would be interpreted as either
x.operator op(y)
in case of member functions, or
operator op(x,y)
in case of friend functions.
No comments:
Post a Comment