In fact, many C + + operators have been overloaded. Eg: using the * operator for an address will get the value stored in this address, and when used for 2 digits, it will be their product. C + + determines which action to take based on the number and type of operands.
C + + allows operator overloading to be extended to user-defined types. For example, allow + to add two objects. The compiler will decide to use the addition definition based on the number and type of operands. Operator overloading can make your code look more natural. For example, adding 2 arrays is a common operation. Typically, you need to use a for loop such as the following:
Copy Code code as follows:
for (int i = 0; i < i++)
Evening[i] = Sam[i] + janet[i]; add element by element
In C + +, however, you can define a class that represents an array and overload the + operator, and then you have the statement:
Total = ARR1+ARR2;
An example of a computational time
Mytime.h
Copy Code code as follows:
#include "stdafx.h"
#include "MyTime.h"
#include <iostream>
Int_tmain (intargc,_tchar*argv[])
{
More economical than importing entire namespaces
Usingstd::cout;
Usingstd::endl;
timeplanning;
Timecoding (2,50);
Timefixing (5,55);
Timetotal;
cout<< "Planningtime=";
Planning. Show ();
cout<<endl;
cout<< "Codingtime=";
Coding. Show ();
cout<<endl;
cout<< "Fixingtime=";
Fixing. Show ();
cout<<endl;
Total=coding. Sum (fixing);
cout<< "coding. Sum (fixing) = ";
Total. Show ();
cout<<endl;
total=coding+fixing;
cout<< "coding+fixing=";
Total. Show ();
cout<<endl;
GetChar ();
Return0;
}
Call
Copy Code code as follows:
#include "stdafx.h"
#include "MyTime.h"
#include <iostream>
Int_tmain (intargc,_tchar*argv[])
{
More economical than importing entire namespaces
Usingstd::cout;
Usingstd::endl;
timeplanning;
Timecoding (2,50);
Timefixing (5,55);
Timetotal;
cout<< "Planningtime=";
Planning. Show ();
cout<<endl;
cout<< "Codingtime=";
Coding. Show ();
cout<<endl;
cout<< "Fixingtime=";
Fixing. Show ();
cout<<endl;
Total=coding. Sum (fixing);
cout<< "coding. Sum (fixing) = ";
Total. Show ();
cout<<endl;
total=coding+fixing;
cout<< "coding+fixing=";
Total. Show ();
cout<<endl;
GetChar ();
Return0;
}
Execution results
Key explanations
1.sum function to declare parameters as references, you can improve the efficiency of running, save memory
2.sum function, the return value cannot be a reference. Because the sum object is a local variable, it will be deleted at the end of the function, so the reference will point to an object that does not exist. Using return type time means that the copy is constructed before the sum is deleted, and the calling function gets his copy.