Bjarne stroustrup, a C ++ designer, has made great efforts to make user-defined types work in the same way as fixed types. This is why you can overload operators, write type conversion function, control value assignment and copy constructor.
When you overload the value assignment operator for the class type, pay attention to the following principles:
1.
Operator = try to return the reference of * this;
2.
Assign values to all data members in operator =;
3.
In operator =, check the assignment to yourself;
For common types, int w, x, y, z; W
= X = y = z = 0; such a serial assignment is equivalent to assigning values w, x, y, and z to 0, which is equivalent to W = (x
= (Y = (Z = 0); for the class type, if you want to support such serial assignment, you need to implement operator =, returns the reference to the Value-assigned object (such overhead is the smallest), which should be:
C & C: Operator = (const
C &){... Return * This ;}
When operator = is initially implemented for a class, we can usually assign values to each data member. However, when the class is upgraded (adding members) or serves as the base class of other classes, operator = "Upgrade" may be forgotten, leading to unpredictable problems in the program, in a derived class, operator = needs to explicitly call the base class operator = or directly assign values to the base class members.
Operator does not consider assigning values to itself during implementation, which may lead to disastrous problems, such as releasing a bucket and applying for new storage data, if a = a (A is a string object) appears in the program, the space of a will be released first, and then the data of a will be copied. At this time, no data exists in, this has a fatal impact on the program. When operator = is implemented, perform the following two checks:
/* This method is more widely used */ C & C: Operator = (const C & RHs) { // Check the assignment of the user If (this = & RHs) return * this; ... }
C & C: Operator = (const C & RHs) { // Check the assignment of the user
If (* This = RHs) // assume that operator = exists.
Return * this; ... }
|