1.4 C++ operator overloading as a function

C++ operator overloading function as class member function

When a class member function, an operator overloaded function uses a member variable of the class as an operand.

Write a demo:
insert image description here
When an operator overloading function is used as a class member function, you need to pay attention: the operator overloading function must be a member function of the class, not an ordinary function or a global function.
C++ operator overloading functions as friend functions

As a friend function, the operator overloading function does not use the member variables of the class as operands, but can access the private member variables of the class.

Write a demo:
insert image description here
When using an operator overloading function as a friend function, you need to pay attention: the operator overloading function must be a global function or a friend function of a class, not a member function.

In C++, operators like assignment, subscript, and function call must be defined as member functions of a class.

However, some operators cannot be defined as member functions of a class, such as stream insertion <<, stream extraction >>, and type conversion operators.

Since the use of friends will destroy the encapsulation of the class, try to use operator functions as member functions.

But considering comprehensive factors, unary operators are generally overloaded as member functions, and binocular operators are overloaded as friend functions.

Kobayashi plans to write the next article: unary operator overloading.

Guess you like

Origin blog.csdn.net/qq_40240275/article/details/131120948