Sie sind auf Seite 1von 8

C++

1
Func%on

Func)on Overloading
C++ allows programmers to dene several func%ons,
each of which uses the same name, provided their
parameter types are dierent
This is called overloading func%ons or func*on
overloading
When an overloaded func%on is called, the C++
compiler selects the appropriate func%on to use by
examining the number, type, and order of the
arguments in the func%on call
Developed By Kriss.

Func)on Overloading
Func%on overloading is commonly used to create
several func%ons of the same name that perform
similar process on dierent types of data
It should be no%ced that each overloaded func%on
must have a diering parameter list
Func%on which dier only in their return types
cannot be overloaded
Developed By Kriss.

Func)on Overloading
// Correct function overload.
int max(int, int, int);
float max(float, float, float);
double max (double , double , double );

// Trying this will cause a compiler error.


int max(int, int, int);
float max(int, int, int);
double max (int, int, int);

Developed By Kriss.

Func)on Overloading
int max(int n1, int n2)
{
if(n1 > n2)
return(n1);
else
return(n2);
}
float max(float n1, float n2)
{
if(n1 > n2)
return(n1);
else
return(n2);
}
Developed By Kriss.

Func)on Overloading
When to use overloading
The purpose of func%on overloading is fairly clear
Func%on overloading allows a similar task to be performed on
dierent parameters using a single func*on name
This allows func%on names to describe the process being
performed without geFng confused by extraneous informa%on
such as the type of data being processed
Whenever there are a series of func*ons that essen*ally do the
same thing, only with dierent types of data, func*on
overloading should be given strong considera*on
Developed By Kriss.

Default Arguments
When invoking a func%on we have had to be
careful to ensure that we use the correct number
and type of arguments in the func%on call
Func%on parameters are ini%alized by seFng
them to appropriate values in the func%ons
prototype

Developed By Kriss.

Default Arguments
#include <iostream>
using namespace std;
int add(int = 7, int = 3);
void main()
{
cout << add(13,12) << endl;
cout << add(40) << endl;
cout << add() << endl;
}
int add(int n1, int n2)
{
return(n1 + n2);
}
Developed By Kriss.

Das könnte Ihnen auch gefallen