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)
“In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.”
—Michel de Montaigne (15331592)