On "function overloading" of

--- --- restore content begins

Function overloading

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 number and type, which automatically determines a function call, the function which is It overloaded.

Why do we need to use "function overloading" of this mechanism?

Need to define different function name if there is no mechanism to function overloading, then the different types of data for the same operation. So that when the call will bring us great inconvenience. We did not see the function overloading in learning C language, because C ++ allows functions similar function with the same function name defined in the same scope, thereby forming a heavy load.

Precautions:

1: shape parameter overloaded functions must be different: a different number or different types.

2: When using function overloading, it is best not to use the default parameter values.

eg;void fun(int length, int width=2,int heigth=3);

        void fun(int length);

When in a fun (1) This form of call fun, the compiler can not overloaded functions that should be performed.

3: Do not define the function of different functions to function overloading, in order to avoid misinterpretation of the results of the calls appear.

Overloading experiment;

Experimental requirements: achieve two integers integers with three sorting and overloads, in ascending order of the sorted result output.

Procedures are as follows:

#include<iostream>
using namespace std;
void rank(int x,int y);
void rank(int a,int b,int c);
int main()
{
 int x,y,a,b,c;
 cin>>x>>y>>a>>b>>c;
 rank(x,y);
 rank(a,b,c);
 return 0;
}
void rank(int x,int y)
{
 if(x>y)
 cout<<y<<" "<<x<<endl;
 else
 cout<<x<<" "<<y<<endl;
}
void rank(int a,int b,int c)
{
 int t;
 if(a>b)
 {
  t=a;
  a=b;
  b=t;
 }
 if(a>c)
 {
  t=a;
  a=c;
  c=t;
 }
 if(b>c)
 {
  t=b;
  b=c;
  c=t;
 }
 cout<<a<<" "<<b<<" "<<c<<endl;
}

operation result:

 

Summary: For function overloading is concerned, it can help us to call functions, I do not remember the name so many ways, but know the function of the method can be passed directly to his different parameters, the compiler You will know exactly what we call a method.

 

 

 

 

 

--- end --- restore content

Guess you like

Origin www.cnblogs.com/byp-520/p/11519915.html