C++ operator overloading basics

  • 2020-04-02 02:16:18
  • OfStack

In fact, many C++ operators have been overloaded. Use the * operator for the address, and you will get the value stored in the address. Use it for two Numbers, and you will get their product. C++ determines which operation to use based on the number and type of operands.

C++ allows operator overloading to be extended to user-defined types. For example, you can add two objects using +. The compiler decides to use an addition definition based on the number and type of operands. Operator overloading can make the code look more natural. For example, adding two arrays is a common operation. Typically, this is done using a for loop like this:


for (int i = 0; i < 20; i++)
evening[i] = sam[i] + janet[i]; // add element by element

But in C++, you can define a class that represents an array and override the + operator, so you have a statement like this:

Total = arr1 + arr2;
An example of calculating time
Mytime. H


#include"stdafx.h"
#include"MyTime.h"
#include<iostream>
int_tmain(intargc,_TCHAR*argv[])
{
//It's more economical than importing the entire namespace
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

The same code at the page code block index 1

The execution result

< img SRC = "border = 0 / / img.jbzj.com/file_images/article/201403/20140312161326.jpg? 2014212161356 ">

Focusing on
1. The sum function declares parameters as references, which can improve operation efficiency and save memory

2. In the sum function, the return value cannot be a reference. Because the sum object is a local variable that is deleted at the end of the function, the reference points to a nonexistent object. Using the return type Time means constructing a copy of sum before deleting it, and calling the function will get a copy of it.


Related articles: