Use function overloading

Overloaded function

1: What is overloaded function?

Overloaded function refers to two or more functions, with the same function name, but a different number or type parameter, the compiler according to the best matching parameter arguments and the type and number of calls automatically determined which one function, which is overloaded function.

2: overloaded function of what use is it?

We all know the usual language in action can be used to represent a lot of different things, such as for example a eraser, can be said to wipe the table, your shoes on and so forth action, is there with a similar function in c ++ in does, in fact, is there, it is overloaded function, and this function which represents the earlier example is erased, it can handle different data types, which makes the program so that we can be of different functions given the same function name, the computer will automatically match specific functions according to the type and number of arguments 2 compile time.

3: overloaded functions to achieve

The following example e.g.

#include<iostream>
using namespace std;
int abc(int a, int b)
{
    int sum;
    sum = a + b;
    return sum;
}
float abc(float a, float b)
{
    float sum;
    sum = a + b;
    return sum;
}

Here we define the function takes two together, but a closer look will find two functions have the same function name, but the function of different types of variables at play, the first function is shaping values ​​are summed, the second is the summation of floating point numbers, this is in fact the definition of overloaded functions so we went to see the complete code

#include<iostream>
using namespace std;
int abc(int a, int b)
{
    int sum;
    sum = a + b;
    return sum;
}
float abc(float a, float b)
{
    float sum;
    sum = a + b;
    return sum;
}
void main()
{
    int a, b;
    float c, d;
    double sum1,sum2;
    cout << "请输入abcd的值" << endl;
    cin >> a  >> b  >> c  >> d;
    sum1 = abc(a, b);
    sum2 = abc(c , d);
    cout <<"a和b的合为"<< sum1 << endl<<"c和d的合为" << sum2 << endl;
}

As shown, I define the values ​​of the four plastic and floating point numbers and call functions with its statement that did not, but directly invoke the same function function name, then we look at the results

We can see the same function name when calling the function, although it is used on a computer, but the result of their own data types and find out the function of a judge in overloaded functions that most closely matches to be calculated, which is overloaded function

4 What kind of problems can be avoided using function overloading

So overloaded function can solve any problem then, function overloading because the automatic matching system so you can solve a variety of data types of calculations can be used to solve many preset function, the more trouble you call, bad call and other issues .

Guess you like

Origin www.cnblogs.com/bjfybjn/p/11521149.html