Function overloading in C++
In actual code writing, sometimes the same functional function may process different object types, so the function needs to be re-implemented, which will make the code more complicated. In order to solve this problem, C++ supports function overloading. to solve this problem.
For example, for an arithmetic sum problem, you need to customize a function to receive the incoming data and sum it up. But as an independent module, how do you know what type of data the caller has passed in? It may be integer data, of course it may be floating point type data, or it may be an integer and a floating point type (it is not yet known which one is the integer type and which one is the floating point type), and a comprehensive approach is to use various Each type of formal parameter function must have one function defined, that is, two int types, two double types, the first int and the second double, and the first double and the second int. Define four functions to Implementation, for example, the names are: Add_double_double(), Add_int_double(), Add_int_int(), Add_double_int(), etc. Doesn’t this seem confusing?
Then, the emergence of function overloading in C++ solves this problem very well. Function overloading is two or more functions with the same function name but different parameter types or numbers. Based on the type and number of parameters, the most suitable function is automatically selected for binding calls, and the selection is automatically implemented.
For example, in the addition example just now:
#include<iostream>usingnamespacestd;intadd(inta,intb){cout<<(int,int)t;returna+b;}doubleadd(doublea,doubleb){cout<<(doble,double)t;returna+ b;}doubleadd(doublea,intb){cout<<(double,int)t;returna+b;}doubleadd(inta,doubleb){cout<<(int,double)t;returna+b;}intmain (){cout<<add(2,3)<<endl;cout<<add(2.9,15.3)<<endl;cout<<add(10,9.9)<<endl;cout<<add(11.5,5 )<<endl;return0;}
The running results are as follows:
Please read the code carefully. In order to confirm which function is executed, we add a cout output statement inside the function to distinguish which function is called.
Everyone must experiment on your own to understand the code!