Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Operator overloading
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Examples== In this case, the addition operator is overloaded to allow addition on a user-defined type {{code|Time}} in [[C++]]: <syntaxhighlight lang=Cpp> 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; } </syntaxhighlight> Addition is a [[binary operation]], which means it has two [[operand]]s. In C++, the arguments being passed are the operands, and the {{code|temp}} object is the returned value. The operation could also be defined as a class method, replacing {{code|lhs}} by the hidden {{code|this}} argument; However, this forces the left operand to be of type {{code|Time}}: <syntaxhighlight lang=Cpp> // The "const" right before the opening curly brace means that |this| is not modified. Time Time::operator+(const Time& rhs) const { Time temp = *this; // |this| should not be modified, so make a copy. 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; } </syntaxhighlight> Note that a [[Unary operation|unary]] operator defined as a class method would receive no apparent argument (it only works from {{code|this}}): <syntaxhighlight lang=Cpp> bool Time::operator!() const { return hours == 0 && minutes == 0 && seconds == 0; } </syntaxhighlight> The less-than (<) operator is often overloaded to sort a structure or class: <syntaxhighlight lang=Cpp> class Pair { public: bool operator<(const Pair& p) const { if (x_ == p.x_) { return y_ < p.y_; } return x_ < p.x_; } private: int x_; int y_; }; </syntaxhighlight> Like with the previous examples, in the last example operator overloading is done within the class. In C++, after overloading the less-than operator (<), [[sort (C++)|standard sorting functions]] can be used to sort some classes.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)