Вы находитесь на странице: 1из 2

6.

14 Overloading Function Names

Function overloading is the ability to have more than one function with the same name within
the same scope.

Beware: The number and type of the arguments must be significantly different.

#include <iostream>
using namespace std;

void DatePrint(int day, int month, int year) {


cout << month << "/" << day << "/" << year;
return;
}

void DatePrint(int day, string month, int year) {


cout << month << " " << day << ", " << year;
return;
}

int main() {
DatePrint(30, 7, 2012); cout << endl;
DatePrint(30, "July", 2012); cout << endl;
return 0;
}

How does it work? The number and type of arguments become part of the name of the
function. This is called the function signature and is done with “name mangling”.

The DatePrint function name has been overloaded, meaning two definitions have been
specified for a single function name. The compiler determines which function to call based on
the argument types. DatePrint(30, 9, 2013) has arguments "int, int, int" and thus calls the first
function. DatePrint(30, "July", 2012) has arguments "int, string, int" and thus calls the second
function.
Overloading a function name with more than two definitions is allowed, as long as each
function's parameter types are distinct. Thus:
 Adding the function void DatePrint(int month, int day, int year, int style) above would
be allowed because its parameter types of "int, int, int, int" differs from the existing
types "int, int, int" and "int, string, int".
 Adding the function void DatePrint(int month, int day, int year) above would generate a
compiler error, because two functions would have the same parameter types of "int, int,
int" (the names of parameters and/or arguments are irrelevant).
 Adding the function void DatePrint(string. month, int year = 2013) is fine.
 Adding the function void
 Adding the function void DatePrint(int month, int day, int year, int style=0) above
would generate a compiler error because the compiler cannot determine if the function
call DatePrint(7, 30, 2012) should go to the "int, int, int" function or to that new "int, int,
int, int" function with a default value for the last parameter.

Exercise:
Given:
#include <iostream>
using namespace std;

double average(double valOne, double valTwo)


{
return (valOne + valTwo)/2.0;
}

int main(void)
{
cout<< average(1.5, 3.5)<<endl;

int stope; cin>>stope;


}
Overload function average so that it will return average of three numbers:
average(10.1,20.5, 16.3)

Вам также может понравиться