1. What Is operator overloading
Operator overloading is a function overload.
The format of the operator function:
Operatorop (Argument-list)
For example, the operator+ () overload + operator.
The OP, which must be a valid C + + operator, such as [email protected] () will error because there is no @ operator in C + +.
2. Use of overloaded operators
As shown in the following example:
class test{publicoperator+ (Test &Test);}
There are two ways to call an operator function:
Test T1;
Test T2;
1) normal function call
Test t3 = t1.operator+ (T2);
2) the operator+ () function in the operator mode call, which is essentially called 1)
Test t3 = t1+t2;
3. Example of operator overloading
The example code is as follows, the + operator overload, which calculates the time division addition.
Mytest.h
#pragma onceclass time{ private : int hours; int minutes; public : Time (); Time ( int h,int m=0 ); Time operator + (const time&t ) const ; void Show () const ;};
MyTest.cpp
#include"mytest.h"#include<iostream>Time::time () {hours=minutes=0;} Time::time (intHintm) {Hours=h; Minutes=m;} Time::operator+(ConstTime &t)Const{time sum; Sum.minutes= minutes+t.minutes; Sum.hours= hours+t.hours+sum.minutes/ -; Sum.minutes%= -; returnsum;}voidTime::show ()Const{std::cout<"hours,"<<minutes<<"minutes"<<Std::endl;}
Test.cpp
#include"mytest.h"#include<iostream>intMain () {time planning; Time Coding (2, +); Time Fixing (5, -); Time Total; Total= coding+fixing; Std::cout<<"coding+fixing ="; Total. Show (); Total= Coding.operator+(fixing); Std::cout<<"coding.operator+ (fixing) ="; Total. Show (); Total= coding+fixing+coding; Std::cout<<"coding.operator+ (fixing) ="; Total. Show (); return 0;}
Output Result:
4. Considerations for Operator Overloading:
1) The overloaded operator must be a valid C + + operator
2) At least one of the operator operands is a user-defined type
This is to prevent overloading of standard type operators
If you overload the subtraction operator (-) to calculate the two double and not the difference, it is not allowed.
3) cannot violate the original rules of the operator
In the case of modulo operators (%), there must be two operands.
4) Some operators do not allow overloading
such as: sizeof,::,: Et
Reference: "C + + primer.plus" pp.381-390
C + + operator overloading detailed