First job: C ++ function overloading

Function overloading

Function overloading is a new concept in C language learning is not involved. We often encounter such a problem in programming: We've written a function to call when ready to prepare, once the need to pass different data types of parameters, a function can not be achieved, we must rewrite another or more named do not function approximation function in order to achieve its operation, it is clear that, for achieving the same function parameter passing different data types but need to call functions with different names, which adds unnecessary difficulty. At this time, function overloading to provide us a solution.

(1) Definition: two or more functions with the same names, but different type or number parameter, based on the best match compiler arguments and the type and number of parameters, which automatically determines a function call.

With the following function overloading, we approximate but different function parameters, the need for a different function named in the function name function, the compiler will automatically match.

For example, a function of x + y implementing the functions:

#include<iostream>
using namespace std;
int add(int a, int b)
{
    return a + b;
}
double add(double a, double b)
{
    return a + b;
}
int main()
{
    int a, b;
    double c, d;
    cout << "输入两个int值" << endl;
    cin >> a >> b;
    cout << "输入两个double值" << endl; 
    CIN >> >> C D; 

    COUT << " int values becomes " << the Add (A, B) << endl; 
    COUT << " Double values becomes " << the Add (C , D) << endl; 

    return  0 ; 
}

The output is:

 

 Code compilation can be shown that: call the same function name for the function, the compiler will automatically match.

Note: The parameters of overloaded functions must be different in terms of the type or number of arguments, if the same function name, parameter types are the same, at compile time it would be considered a syntax error.

Reload the correct form of the function:

int  add(int x,int y);
double add(double x,double y);

or:

you add ( you get, you y);
you add ( you get, you y, you z);

 It needs extra attention is not the function definition for the different functions of overloaded functions, in order to avoid misinterpretation of the results of calling the function appears confused.

(2) When using function overloading, to avoid ambiguity occurs, which causes the compiler syntax error.

 

statement:

you add ( you get, you y = 1 , you z = 2 ); 

you add ( you x);

transfer:

add(1);

At this syntax error will occur.

(3) summarizes the situation appears ambiguous:

1, the number of agreement parameter, or a parameter name just a different return value
2, when there is a heavy load function parameter has default parameters
3, overloaded function parameter or a value-reference to pass type at the same positions, respectively.

 

Guess you like

Origin www.cnblogs.com/lhlcnblogs/p/11515380.html