Operator Overloading is a form of C ++ polymorphism. Operator Overloading extends the concept of overloading to operators, allowing the C ++ operator to have multiple meanings. In fact, many C ++ operators have been overloaded. For example, if you use the * operator for an address, you will get the value stored in this address. When you use the * operator for two numbers, the result will be the product of them. C ++ determines which operation to use based on the number and type of operands.
C ++ allows you to extend Operator Overloading to user-defined types. For example, you can use + to add two objects. The compiler uses addition definitions 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. Generally, the following for loop is required:
( i = ; i < ; i++= sam[i] + janet[i];
However, in C ++, you can define a class that represents an array and reload the + operator, so there is a statement like this:
total = arr1+arr2;
An example of computing time
Mytime. h
once MYTIME_H_ Time( Time( h, ~Time( AddMin( AddHr( Reset( h, Time Sum( Time &t); Time + (Time &t);
Mytime. cpp
#include #include <iostream> #include Time::Time( hours = minutes = Time::Time( h, hours = minutes = Time::~Time( Time::AddMin( minutes += hours += minutes/ minutes %= Time::AddHr( hours += Time::Reset( h, hours = minutes = std::cout<
Call
#include #include #include <iostream> _tmain( argc, _TCHAR* Time coding(, Time fixing(, cout << cout << cout << cout << cout << cout << total = cout << cout << total = coding + cout << cout << }
Execution result
Important explanations
1. the parameter is declared as a reference in the sum function, which improves the running efficiency and saves memory.
2. In the 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 a non-existent object. Using the return type Time means constructing a copy before deleting sum, and calling the function will get its copy.
References
C ++ Primer Plus (Chapter 6)