You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/posts/cpp-learn.md
+80Lines changed: 80 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3875,3 +3875,83 @@ Name is a Derived
3875
3875
3876
3876
### 21.8. Printing inherited classes using operator<<
3877
3877
- Refer to the learncpp.com
3878
+
3879
+
## 22. Overloading Operators
3880
+
- Almost any existing operator in C++ can be overloaded. The exceptions are:` conditional (?:), sizeof, scope (::), member selector (.), pointer member selector (.*), typeid, and the casting operators`.
3881
+
- We can only overload the operators that exist.
3882
+
- At least one of the operands in an overloaded operator must be a user-defined type.
3883
+
3884
+
- Overloading the plus operator (+) is as simple as declaring a function named `operator+`, giving it two parameters of the type of the operands we want to add, picking `an appropriate return type`, and then writing the function.
3885
+
3886
+
- Not everything can be overloaded as a friend function: The assignment (=), subscript ([]), function call (()), and member selection (->) operators must be overloaded as member functions, because the language requires them to be.
3887
+
3888
+
> The following rules of thumb can help you determine which form is best for a given situation:
3889
+
If you’re overloading assignment (=), subscript ([]), function call (()), or member selection (->), do so as a member function.
3890
+
If you’re overloading a unary operator, do so as a member function.
3891
+
If you’re overloading a binary operator that does not modify its left operand (e.g. operator+), do so as a normal function (preferred) or friend function.
3892
+
If you’re overloading a binary operator that modifies its left operand, but you can’t add members to the class definition of the left operand (e.g. operator<<, which has a left operand of type ostream), do so as a normal function (preferred) or friend function.
3893
+
If you’re overloading a binary operator that modifies its left operand (e.g. operator+=), and you can modify the definition of the left operand, do so as a member function.
0 commit comments