One 、 Basic knowledge of operator overloading

In the previous blog post

C++ The template of learning notes (1)—— From function overloading to function templates

in , Introduces the concept of function overload , Definition and usage , function overloading ( It's also called functional polymorphism ) That is to enable users to define multiple signatures with the same name ( parameter list ) Different functions , The goal is to perform the same operation on different types of parameters with only one function of the same name .

Operator overloading , That is to make the same operator do different operations when facing different types of data ( Function overloading is the same operation ), Let the same operator have multiple functions . In fact, many of the operators we often use have been overloaded , for example , take * For address , You will get the value stored in this address ; But when you use it for two numbers , What we get is the product of them .

C++ Allows operator overloading to be extended to user-defined types , If allowed to use + Add two objects , The compiler determines which addition definition to use based on the number and type of operations .

The format of operator overloading is as follows :

operator Operator ();

for example ,operator+() heavy load + Operator ,operator-() heavy load - Operators, etc . But the overloaded operator must be valid C++ Operator , You can't create a new symbol of your own .

Two 、 Example of operator overloading

Suppose you write a blog , In the morning it took 1 Hours 42 Minute code , In the afternoon it took 2 Hours 33 Minutes to modify , To calculate the total time spent , It's obviously consistent with the concept of addition , But the unit to add is a mixture of hours and minutes , Does not match the built-in addition type . Adopt a usage to deal with the addition of Time class . As a contrast , First, use the normal method , Create a sum() Function of , Then we introduce the use of overloaded operators .

Function method :

 //mytime0, Operator overload not used 
#ifndef MYTIME0_H
#define MYTIME0_H class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m = );
void addMin(int m);
void addHr(int h);
void reset(int h = , int m = );
Time sum(const Time & t ) const;
void show() const;
}; #endif
 #include <iostream>
#include "mytime0.h" Time::Time()
{
hours = minutes = ;
} Time::Time(int h, int m)
{
hours = h;
minutes = m;
} void Time::addMin(int m)
{
minutes += m;
hours += minutes / ;
minutes %= ;
} void Time::addHr(int h)
{
hours += h;
} void Time::reset(int h, int m)
{
hours = h;
minutes = m;
} Time Time::sum(const Time & t) const
{
Time result;
result.minutes = minutes + t.minutes;
result.hours = hours + t.hours +result.minutes / ;
result.minutes %= ;
return result;
} void Time::show() const
{
std::cout << hours << " hours, " << minutes << " minutes";
}
 /*usetime0*/
#include <iostream>
#include "mytime0.h" int main()
{
using std::cout;
using std::endl;
Time planning;
Time coding(, );
Time fixing(, );
Time total; cout << "planning time = ";
planning.show();
cout << endl; cout << "coding time = ";
coding.show();
cout << endl; cout << "fixing time = ";
fixing.show();
cout << endl; total = coding.sum(fixing);
cout << "coding.sum(fixing) = ";
total.show();
cout << endl; return ;
}

Running results :

Operator overloading methods :

The examples given here are relatively simple , We just need to put sum() Change the name to operator+() that will do . The program list is as follows :

 //mytime0, Operator overload not used 
#ifndef MYTIME0_H
#define MYTIME0_H class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m = );
void addMin(int m);
void addHr(int h);
void reset(int h = , int m = );
Time operator+(const Time & t ) const;
void show() const;
}; #endif
 #include <iostream>
#include "mytime0.h" Time::Time()
{
hours = minutes = ;
} Time::Time(int h, int m)
{
hours = h;
minutes = m;
} void Time::addMin(int m)
{
minutes += m;
hours += minutes / ;
minutes %= ;
} void Time::addHr(int h)
{
hours += h;
} void Time::reset(int h, int m)
{
hours = h;
minutes = m;
} Time Time::operator+(const Time & t) const
{
Time result;
result.minutes = minutes + t.minutes;
result.hours = hours + t.hours +result.minutes / ;
result.minutes %= ;
return result;
} void Time::show() const
{
std::cout << hours << " hours, " << minutes << " minutes";
}
 /*usetime0*/
#include <iostream>
#include "mytime0.h" int main()
{
using std::cout;
using std::endl;
Time planning;
Time coding(, );
Time fixing(, );
Time total; cout << "planning time = ";
planning.show();
cout << endl; cout << "coding time = ";
coding.show();
cout << endl; cout << "fixing time = ";
fixing.show();
cout << endl; total = coding + fixing; // Through operators + No. calls the overloaded operator directly
cout << "coding + fixing = ";
total.show();
cout << endl; Time morefixing(, );
cout << "morefixing time = ";
morefixing.show();
cout << endl; total = morefixing.operator+(total);// It can also be called by function name
cout << "morefixing.operator+(total) = ";
total.show();
cout << endl; return ;
}

All in all ,operator+() The function name makes it possible to call it using a function representation or an operator representation .

If t1,t2,t3,t4 All are Time object , Can you do this :

t4 = t1 + t2 +t3;

Let's analyze it carefully ,+ It's a left to right operator , According to the function in the above code , The above statement is first converted to :

t4 = t1.operator+(t2 + t3); //t1 call operator+() function 

Then continue to convert to :

t4 = t1.operator+(t2.operator+(t3)); //t2 call operator+() function 

Is the above statement legal ? It's legal, of course , because  t2.operator+(t3) Return to one Time object , yes t2 and t3 And , The object becomes a function call again t1.operator+() Parameters of , The call returns t1 And to express t2 and t3 Sum of Time The sum of the objects . The last return value is t1,t2,t3 The sum of the , It's exactly what we want . It can be seen that , Operator overloading is more natural than functions .

3、 ... and 、 The limitation of overloading

Most of the C++ Operators can be overloaded in this way . But there is no absolute freedom . The main limitations are as follows :

  1. At least one of the operands of the overloaded operator is a user-defined type . This will prevent users from overloading operators for standard types . If there is no such limitation , We can - Overload is two double Add up , Not their difference , It's a mess .
  2. Using operators cannot violate the original syntax rules of operators . for example . The modulo operator cannot be (%) Overload to use an operand :% x. At the same time, you can't change the priority of the operator .
  3. Can't create a new operator . for example , Don't define operator**() Function to express exponentiation .
  4. The following operators cannot be overloaded :
    • sizeof  sizeof Operator
    • .   member operator
    • .* Member pointer operator
    • :: Scope resolution operator
    • ?: Conditional operator
    • typeid One RTTI Operator
    • const_cast
    • dynamic_cast
    • reinterpret_cast
    • static_cast

5. Most operators can be overloaded by member or non member functions , But the following operators can only be overloaded by member functions

= Assignment operator

() Function call operators

[] The following table shows the operators

-> Operators that access class members through pointers .

C++ Learn more about operator overloading in notes

  1. C++ Basics Learning notes 5 : Overloaded operator overloads

    C++ Basics Learning notes 5 : Overloaded operator overloads What is operator overloading Using the same operator to complete different functions, that is, the same operator can have different functions is called operator overloading . Operator overloading is a manifestation of static polymorphism . Rules for operator overloading Overload formula ...

  2. Wu Yuxiong -- It's natural C++ Language learning notes :C++ Overloaded operators and overloaded functions

    C++ Allows multiple definitions to be specified for a function and operator in the same scope , They are called function overloading and operator overloading . Overload declaration refers to a declaration with the same name as a function or method previously declared in the scope , But their parameter lists and definitions ( Realization ) No ...

  3. 《Inside C#》 note ( 11、 ... and ) Operator overloading

    Operator overloading is similar to previous indexers , The purpose is to make the language itself more convenient and direct to use , It's also a grammatical sugar . One Operator overloading (Operator Overloading) The existence of operator overloading , So that the existing operators can be redefined ...

  4. C++ Way of learning — Operator overloading ( Two ) Operator overloading as a member function and friend function of a class

    ( according to <C++ Programming >( Tan Haoqiang ) Arrangement , The arranger : Huake Xiaotao ,@http://www.cnblogs.com/hust-ghtao Reprint please indicate ) There are two ways to handle operator overloaded functions :(1) Put operator ...

  5. C++ Way of learning — Operator overloading ( One ) Concept 、 Methods and rules

    ( according to <C++ Programming >( Tan Haoqiang ) Arrangement , The arranger : Huake Xiaotao ,@http://www.cnblogs.com/hust-ghtao Reprint please indicate ) 1    What is operator overloading Let's start with what overload is ...

  6. C++ Primer note 10_ Operator overloading _ Assignment operator _ Get into / The output operator

    1. Praise value operators First of all, we introduce the operator overloading that we will talk about later . The previous section said constructors . copy constructor : If a class wants to have better control . You need to define your own constructor . copy constructor . Destructor . Of course , And the assignment operator . The three letters that are often said ...

  7. The new standard C++ Program design, reading notes _ Operator overloading

    form return type operator Operator ( Formal parameter table ) { …… } Operator overloading (1) The essence of operator overloading is function overloading (2) Can be overloaded as a normal function , It can also be overloaded as a member function class Complex { publ ...

  8. scala Learn to remember 7 - Operator overloading

    Grammatically scala There is no operator . It was mentioned in the previous section scala The operator for is actually the method name , Such as 1 + 2 It's actually 1.+(2). We can think of it as an operator , Because scala A feature of : If the parameter of the method is less than ...

  9. C++ Primer note 13_ Operator overloading _ summary

    summary : 1. Operators that cannot be overloaded : . and .* and ?: and ::  and sizeof and typeid 2. There are two basic options for overloading operators : Class member function or friend function , Suggested rules such as the following : Operator It is recommended to use ...

Random recommendation

  1. call() And archetypal inheritance

    1.call() call() Method accepts two arguments ,obj and arg such as functionA.call(obj,arg)    That is to say, run now ( perform )functionA This method , however functionA The square inside ...

  2. BZOJ 1833 count Number counting

    sb digit dp. #include<iostream> #include<cstdio> #include<cstring> #include<algorith ...

  3. How to make cron Send an email when the task goes wrong

    If set MAILTO,cron The standard output and standard error output of the task will be redirected to the mailbox ( That is to send an email ). But if you just want to get an error alert email -- That is, the task will not be sent during normal execution , Send only when error occurs -- How should it be realized ? The method is very ...

  4. ZStack Programming skills in

    1. Macros used like functions // This macro , Used by other macros , Construct a correct and valid expression . This is suitable for the combination of some discrete statements , Not suitable for function renaming #define st(x)      do { x } while ...

  5. About C Used in language Keil Software production Lib Some experiences of library files

    1. About stopping LIB Some experiences of library files 1. How to generate a project lib file : 2. A generation lib File project can call functions that do not exist in this project , Only need .h The prototype of these nonexistent functions is declared in the file , And then call this lib writing ...

  6. jetty The domain name of the server access system

    jetty-env.xml=><Set name="contextPath">/epps-compensation-backend</Set> This decision ...

  7. pyqt4 Realization tab Interface switching

    ( turn :https://segmentfault.com/q/1010000005143428)

  8. Inherited prototype And _proto_

    The core of inheritance is the prototype chain , Its basic idea is to use prototypes to let one reference type inherit the properties and methods of another . example :SubType.prototype = new SuperType (); var instance = ...

  9. RabbitMQ User addition, deletion and permission control

    RabbitMQ User addition, deletion and permission control User role classification none: Unable to log on to the console Cannot access management plugin, It's usually ordinary producers and consumers . management: General manager . You can only log in ...

  10. cookie Set the method to expire at a specific point in time

    Suppose the demand is : That night 0:00 Be overdue . Method : Get that night 0:00 A time at this point in time . function getNextDate(){        var d = new Date(),      ...