C++ operator function overload
- Operator function overload
- Operator function
- Binocular operator
- Monologic operator
- Binocular operator function overload
- Member functions
- Global functions
- Friendly function
- Binocular operator of assignment type
- Monologic operator function overload
- Member functions
- Global functions
- Front++/-
- After ++/-
- Input and output operator overload
- Overloading of special operators
- Subscript operator[]
- Function operator()
- Dereference operator*, member access operator->
- Smart pointer
- new/delete/new[]/delete[] operator overload
- Limitations of overload operators
- Suggestions on operator overloading
Operator function overload
Operator function
1. Operators for class-type objects in C++. Since they definitely do not support real operations, the compiler will translate them into functions. This is called an operator function (operator function).
2. The compiler translates operators into operator functions, and can design its unique operation functions for custom class types.
3. In fact, various operators already have some functions, and the one that implements it again is called operator overloading.
Binocular operator
a+b
Member functions
+(b);
Global functions
operator+(a,b);
Monologic operator
!a
Member functions
!(void);
Global functions
operator!(a);
Binocular operator function overload
Member functions
const class operator#(const class & that) const
{
return class (parameter #parameter);
}
Note: The operation result of the binocular operator is an rvalue, the return value should be added to const, and then for the const object to call parameters, the function should also have the const attribute
class Point
{
int x;
int y;
public:
Point(int _x=0,int _y=0)
{
x = _x;
y = _y;
}
const Point operator+(const Point& that) const
{
return Point(that.x+x,that.y+y);
}
};
Global functions
Class operator#(const class & a,const class & b)
{
}
Note: Global functions are not member functions, and may access private members of the class. To solve this problem, you can declare the function as a friend function of the class (a friend function is not a member function).
class Point
{
int x;
int y;
public:
Point(int _x=0,int _y=0)
{
x = _x;
y = _y;
}
friend const Point operator+(const Point& a,const Point& b);
};
const Point operator+(const Point& a,const Point& b)
return Point(a.x+b.x,a.y+b.y);
}
Friendly function
1. When an external class wants to access a private member of the class (public/protected/private), the function you are in needs to be declared as a friend, but the friend is just a friend and has no actual ownership, so it only has access (the root cause is that it does not have this pointer).
2. Declaration of friendly function: Write a copy of the function declaration into the class, and add the friend keyword before the declaration. Using friendly function can not only define the operator function as global, but also ensure the encapsulation of the class.
Note: Friend functions and member functions do not constitute an overload relationship because they are not in the same scope.
Binocular operator of assignment type
1. Get the call method of single parameter construction and assignment operators.
String str = "sss"; // Single parameter construct will be called, but the assignment operator will not be called.
str = "hehe"; // Will call the assignment operator
2. The left operand cannot have a const attribute
1. Member functions cannot be regular functions
2. The first parameter of the global function cannot have a const attribute
class Point
{
int x;
int y;
public:
Point(int _x=0,int _y=0)
{
x = _x;
y = _y;
}
/*
const Point& operator+=(const Point& that)
{
x += ;
y += ;
return *this;
} // Member functions
*/
friend const Point& operator+=(Point& a,const Point& b);
};
const Point& operator+=(Point& a,const Point& b)
{
a.x += b.y;
a.y += b.y;
return a;
}
Monologic operator function overload
-,~,!,&,*,->,.
Member functions
Object.operator#(void)
const class operator#(void)
{
}
Global functions
const class & operator#(const class & that)
{
}
Front++/-
Class & operator#(void)
{
}
Class & operator#(Class & that)
{
}
class Point
{
int x;
int y;
public:
Point(int _x=0,int _y=0)
{
x = _x;
y = _y;
}
/*Point& operator++(void)
{
++x;
++y;
return *this;
} // Member functions
*/
friend Point& operator++(Point& that);
};
Point& operator++(Point& that)
{
that.x++;
that.y++;
return that;
}
After++/-
const class & operator#(int)
{
}
const class & operator(class & that,int)
{
}
class Point
{
int x;
int y;
public:
Point(int _x=0,int _y=0)
{
x = _x;
y = _y;
}
/*Point operator++(int)
{
Point temp(x,y);
x++;
y++;
return temp;
} // Member function, int is a dumb
*/
friend Point operator++(Point& that,int);
};
Point operator++(Point& that,int)
{
Point temp(that.x,that.y);
that.x++;
that.y++;
return temp;
}
Input and output operator overload
1. cout is an object of type ostream, cin is an object of type istream
2. If the input/output operator is a member function, the caller should be ostream/istream, and we do not have the right to add the code of the standard library, so the input/output operator can only be defined as a global function.
Note: During the input and output process, cin/cout will record the error flag, so the const attribute cannot be added.
ostream& operator<<(ostream& os,const class&p)
{
}
isstream& operator>>(istream& is,class&p)
{
}
class Point
{
int x;
int y;
public:
Point(int _x=0,int _y=0)
{
x = _x;
y = _y;
}
friend ostream& operator<<(ostream& os,const Point& p);
friend istream& operator>>(istream& is,Point& p);
};
ostream& operator<<(ostream& os,const Point& p)
{
return os << p.x << "," << p.y;
}
istream& operator>>(istream& is,Point& p)
{
cout << "Please enter the value of x:";
is >> p.x;
cout << "Please enter the value of y:";
is >> p.y;
return is;
}
Overloading of special operators
Subscript operator[]
Subscript operators are often used to obtain elements in the following formats in containers.
Type & operator[](int i)
Function operator()
If a class overloads function operators, its object can be used like a function. The number of parameters and return value types can be uncertain. It is the only operator that can have default parameters.
Dereference operator*, member access operator->
If a class overloads * and ->, its objects can be used like pointers. The so-called smart pointer is a class object that supports dereference and member access operators.
Smart pointer
Disadvantages of regular pointers:
When a regular pointer leaves its scope, only the space occupied by the pointer will be released, and it is not certain whether the memory space it points to can be released. In some special cases (human, special business logic) free or delete is not executed, a memory leak will occur.
Advantages of smart pointers:
Intelligent pointer is a class-type object that encapsulates regular pointers. When it leaves scope, its destructor is responsible for freeing the dynamic memory pointed to by the regular pointer (its destructor will be executed correctly only if the smart pointer is created in the correct way).
Similarities between smart pointers and regular pointers:
All support * and -> operations
Differences:
At any time, an object can only point to one smart pointer, while a regular pointer can point to multiple times.
The assignment operation of smart pointers requires special processing (deep copy).
class Int
{
int val;
public:
Int(int val=0):val(val){}
Int& operator=(const int val)
{
this->val = val;
return *this;
}
~Int(void)
{
cout << "Int's destructor" << endl;
}
friend ostream& operator<<(ostream& os,Int& n);
};
ostream& operator<<(ostream& os,Int& n)
{
return os << n.val;
}
class IntPointer
{
Int* ptr;
public:
IntPointer(Int* ptr):ptr(ptr){}
Int& operator*(void)
{
return *ptr;
}
~IntPointer(void)
{
delete ptr;
}
};
int main()
{
Int* num = new Int(100);
IntPointer p = num;
cout << *p << endl;
*p = 20;
cout << *p << endl;
}
new/delete/new[]/delete[] operator overload
1. The default heap memory manager in C++ is slow, and reloading new and delete underlying layers can improve the running speed.
2. An exception occurs when new fails, and for safety each time you use new, exception capture should be performed. Overloading new operators only requires error processing in the operator function.
3. Some classes that occupy relatively small bytes, frequent use of new may generate a large number of memory fragments. After overloading the new operator, the number of bytes applied can be appropriately expanded to reduce the probability of memory fragmentation.
4. Overload new/delete can record the information of heap memory usage
5. Overload delete can detect information when the memory is released failed and memory leak is detected.
class Test
{
void* ptr;
public:
Test(const int val){}
Test(void)
{
cout << "Constructor" << endl;
}
~Test(void)
{
cout << "Destructor" << endl;
}
static void* operator new(size_t size)
{
printf("Create heap memory %d bytes\n",size);
malloc(size);
}
static void operator delete(void* ptr)
{
cout << "Release Memory" << endl;
free(ptr);
}
};
int main()
{
Test* p1 = new Test;
p1 = NULL;
delete p1;
}
Limitations of overload operators
1. Operators that cannot be overloaded
Domain Qualifier::
Direct member access operator.
Three-eye operator?:
Byte length operator sizeof
Type information operator typeid
2. Overloaded operators cannot modify the priority of operators
3. Cannot overload all basic types of operator operations
4. The number of parameters of the operator cannot be modified
5. No new operators can be invented
Suggestions on operator overloading
1. When overloading operators, you should determine the specific parameters, return value, whether they have const attributes based on the actual functions and meaning of the operator, and whether the return value is a reference or a temporary object.
2. The overloaded operator should be reasonable (meaningful) and should be based on practical purposes.
3. The meaning of overloading operators is to make the operation of objects simpler and more convenient and improve the readability of the code.
4. The overloaded operator should be consistent with the functions and operation rules of the default operators, and there should be no anti-human operations.