选择操作符重载的成员和非成员实现

When designing classes to overload operators, it is essential to choose whether to implement the operator as a member or as a regular non-member function.

Must be defined as regular member functions

Operators such as assignment (=), subscript ([]), call (()), and member pointer (->) must be defined as members. Defining these operators as non-member functions will result in a compile-time error.

Compound assignment operators (+=/-=/*=//=) are generally recommended to be defined as members of the class.

It is not strictly necessary to do this; defining non-member compound assignment operators will not result in an error.

Other operators that modify object state or are closely related to a given type.

Operators such as increment, decrement, and dereference are typically recommended to be defined as class members.

IO operators must be non-member functions

When we define IO operators as member functions, the left operand can only be an object of that class type.

This is the opposite of our usual approach:

1
2
3
4
// When IO operators are member functions
classObject << cout;
// Common IO usage
cout << classObject;

To use the normal usage method, the left operand must be of the ostream type. If this operator is a member of the class, it must be a member of the ostream class; however, since ostream is part of the standard library, we cannot add members to classes in the standard library.

Symmetric operators, such as *arithmetic operators (+-/), **equality operators (==), relational operators (><), and bitwise operators (&) are best defined as regular non-member functions.

The article is finished. If you have any questions, please comment and communicate.

Scan the QR code on WeChat and follow me.

Title:选择操作符重载的成员和非成员实现
Author:LIPENGZHA
Publish Date:2016/03/21 16:54
World Count:1.4k Words
Link:https://en.imzlp.com/posts/34001/
License: CC BY-NC-SA 4.0
Reprinting of the full article is prohibited.
Your donation will encourage me to keep creating!