#include <iostream>
using namespacestd;classfi{ Public: Fi () {cout<<"Fi::fi ()"<<Endl;}};classfee{ Public: Fee (int) {cout<<"fee::fee (int)"<<Endl;} Fee (Constfi&) {cout<<"Fee::fee (fi&)"<<Endl;} fee&operator=(Constfee& RHS) {cout<<"fee::operator="<<Endl;
if (THIS!=&RHS) {//perform Assignment}
return *this; }};intMain () {Fee Fee=1;//Fee (int)fi fi; Fee Fum=fi;//Fee (Fi);Fum=fi;//first, a fee object is constructed with fi, and then the assignment operation is called.}
Operation Result:
Fee::fee (int) Fi::fi () Fee::fee (fi&) Fee::fee (fi&) Fee::operator =
1, Copying vs. initialization
MyType b;
MyType a = b; Copy Construction
A = b; Assign value
2, Automatic operator= creation
The compiler would automatically create a type::operator= (type) if you don ' t make one.
memberwise Assignment
3, Operator overloading-assignment: must be a member function, assign yourself a value and return yourself
t& T::operator= (const t& RHS) { //check for self assignment if(this!=&rhs) { //perform assignment } return *this;}
The following example shows why you need to judge THIS!=&RHS
class a{ Char *p; Aoperator= (const a& that ) { delete p; P=new [Strlen (THAT.P) +1// If you assign yourself, THAT.P has been deleted; strcpy (P,THAT.P); return *this; }}
4. For classes with dynamically allocated memory declare an assignment operator (and a copy construct or)
--The above content is from "object-oriented Programming C + + course (Onke)"
C + + Class 32 operator overloading-assignment