Operator overloading
Improve the readability of the program
If a class does not provide an assignment operator, the default is to provide a (shallow copy)
If a class provides a copy constructor, an overloaded assignment operation function is also provided
person& person::operator= (const person &other)
{
if (This==&other)
return *this;
Delete[]m_data;
int Length=strlen (other.m_data);
M_data=new char[length+1];
strcpy (M_data,other.m_data);
return *this;
}
C + + language provisions
1 overloaded operators to maintain the meaning of the original operator
2. Can only overload existing operators, cannot add new operators
3. Overloading the operator does not change the original precedence and binding
form of operator overloading
member functions
Friend function
$ operator+ (const rmb& s1,const rmb& s2)
{
unsigned int jf=s1.jf+s2.jf;
unsigned int yuan=s1.yuan+s2.yuan;
RMB Reult (YUAN,JF);
return result;
}
$ operator> (const rmb& s1,const rmb& s2)
{
BOOL Ret=false;
if (S1.yuan>s2.yuan)
return true;
else if (S1.yuan==s2.yuan)
{
if (S1.JF>S2.JF)
return true;
}
return ret;
}
Operator overloading as a member function
An operator that is a member, as an operator of a non-member function, when declared and defined,
One parameter is less formal.
$ rmb::operator+ (const rmb& s)
{
unsigned int c=jf+s.if;
unsigned int d=yuan+s.yuan;
Return RMB (C,D);
}
C + + Provisions: =, (),[],-> These four operators must be of the form of member functions
+ + and--operator overloading
Difference between pre-increment and post-increment
Incremental modification of an object (operand) when using the pre-increment, and then returning the object
When using post-increment, you must return the original object value before the object
class increase
{
Public
Increase (int x): value (x) {}
increase& operator++ (); Pre-increment
Increase operator++ (int); After increment int There's no meaning is the provision just to differentiate before and after increments
/* The meaning of the pre-increment and post-increment operations determines their different return modes.
The former increment operator returns a reference, and the post-increment operator returns the value */
Private
int value;
}
Implementation of member functions of + +
increase& increase::operator++ ()
{
value++; Pre-increment
return *this; Return the original object again
}
Increase increase::operator++ (int)
{
Increase temp (*this); Temporary object holds original object value
value++; Incremental modification of existing objects
return temp;
}
Non-member-type overloads of + +
Friend increase& operator++ (Increase &); Pre-increment
Friend increase operator++ (increase &,int); Post-increment
Friend increase& operator++ (Increase &a)
{
a.value++;
return A;
}
Friend increase operator++ (increase &a,int)
{
Increase temp (a);
a.value++;
return temp;
}
Operator overloading detailed