Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

C++ overload assignment operator and 11 choose 5 platform repair

2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

1. What should be returned by the overloaded assignment function in C++?

11 choose 5 platform repair (enterprise E: 1793 408) class overload assignment operators generally exist as member functions, so what type should the function return? Refer to the assignment operation of the built-in type, such as

Int x,y,z

X=y=z=15

The assignment behavior is equivalent to x = (y = (zip15)), that is, the assignment operation should return a reference to the left Operand. Therefore, in order to be compatible with the built-in type, the overloaded assignment operator in the class should return a reference to the left Operand, namely * this, as shown in the declaration of the overloaded assignment operation function of class A

Class A {}

A & A / A / A

2. Ensure that the overload assignment operation has good behavior

For assignment operations, the first thing you should think about is how to handle self-assignment, especially when the class contains pointer-type data, as follows

Class MyString {

Public:

...

MyString (char * p=NULL)

MyString& operator= (const MyString&)

Private:

Char * str

}

MyString a ("hello")

MyString b ("world")

Abaca

We know that when assigning a value, we first release the resources of the left Operand, and then assign the left Operand according to the right Operand. The assignment function is as follows

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 224

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report