# include
using namespace std;
//the assignment operator overloading
The class Person
{
Public:
The Person (int age)
{
M_Age=new int (age);
}
//parameter must be a reference type, and if the value type, at the end of the function performed when the destructor the pointer (incoming p. _Age) to release the memory space.
Person& Operator=(Person & amp; P)
{
//if you have not release the heap area space, first release
If (m_Age!=NULL)
{
The delete m_Age;
M_Age=NULL;
}
M_Age=new int (* p. _Age);
return *this;
}
To the Person (s)
{
If (m_Age!=NULL)
{
The delete m_Age;
M_Age=NULL;
}
}
Int * m_Age;
};
Void test01 ()
{
The Person p1 (18);
The Person p2 (20);
The Person p3 (30);
P3=p2=p;
//for a custom data types, the equality operator overloading return value must be a reference type
//such as the above code is equivalent to p3. Operator=(p2) operator=(p1)); , including process parameter passing
That Person & amp; P=p2. Operator=(p1); , if the operator=() function returns the value type
//will first create a temporary object in memory temp is used to transfer to receive a copy of the object, and then use the temporary object initialization for reference p
//and temporary object life cycle is very short, only at the end of the current statement released its memory space, then accessed through p temp memory space is illegal operation,
Cout & lt; <"The age of the p1 for:" & lt; <* p1 m_Age & lt;
Cout & lt; <"Age of p2:" & lt; <* the p2 m_Age & lt;
Cout & lt; <"Age of p3:" & lt; <* p3 m_Age & lt;}
Int main (void)
{
Test01 ();
system("pause");
return 0;
}
error:
Case1: when the return value is not a reference type hint:
Binary "=" error C2679: found no accept "Person" type of the right operand operator (or no acceptable conversion)
Case2: when the parameter is not a reference type hint:
CodePudding user response:
The return value is allowed, you wrong, because you aren't judging self assignmentIs T a;
A=a;//this form
When this form when
Your operator=
Put a age deleted in assigned to a, so wrong,
The return value, its defect is more than a copy, inefficient
CodePudding user response:
And your class does not define the copy constructor,The Person & amp; P=p2. Operator=(p1);
By default copy constructor, the compiler will automatically provide, it is the implementation of the target and the original object binary assignment,
P this sentence has been completed and p2 age point to the same memory region, so that when an object after the release, the next object release will go wrong again,
CodePudding user response: