Examples
In this case, the addition operator is overloaded to allow addition on a user-defined type "Time" (in C++):
Time operator+(const Time& lhs, const Time& rhs) { Time temp = lhs; temp.seconds += rhs.seconds; temp.minutes += temp.seconds / 60; temp.seconds %= 60; temp.minutes += rhs.minutes; temp.hours += temp.minutes / 60; temp.minutes %= 60; temp.hours += rhs.hours; return temp; }Addition is a binary operation, which means it has left and right operands. In C++, the arguments being passed are the operands, and the temp
object is the returned value.
The operation could also be defined as a class method, replacing lhs
by the hidden this
argument; however this forces the left operand to be of type Time
and supposes this
to be a potentially modifiable lvalue:
Note that a unary operator defined as a class method would receive no apparent argument (it only works from this
):
Read more about this topic: Operator Overloading
Famous quotes containing the word examples:
“No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.”
—André Breton (18961966)
“Histories are more full of examples of the fidelity of dogs than of friends.”
—Alexander Pope (16881744)
“It is hardly to be believed how spiritual reflections when mixed with a little physics can hold peoples attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.”
—G.C. (Georg Christoph)