Overloaded функции

Overloaded-оптоварена, преклопена функција се добива кога во иста програма се дефинираат неколку функции со исто име, но различни листи на параметри/аргументи.

int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)

Следниов пример има 2 функции за собирање на 2 броја од различен тип


int plusFuncInt(int x, int y) {
  return
 x + y;}

double plusFuncDouble(double x, double y) {
  return
 x + y;}

int main() {
  int
 myNum1 = plusFuncInt(85);
  double
 myNum2 = plusFuncDouble(4.36.26);
  cout << "Int: "
 << myNum1 << "\n";
  cout << "Double: "
 << myNum2;
  return
 0;
}
Наместо да дефинираме 2 функции ќе работиме со преоптоварени функции . Во примерот подолу, ја преоптоваруваме функцијата plusFunc за да работи и за int и за double:

int plusFunc(int x, int y) {
  return
 x + y;}

double plusFunc(double x, double y) {
  return
 x + y;}

int main() {
  int
 myNum1 = plusFunc(85);
  double
 myNum2 = plusFunc(4.36.26);
  cout << "Int: "
 << myNum1 << "\n";
  cout << "Double: "
 << myNum2;
  return
 0;
}

Кога во иста област на важење има повеќе преклопени функции, за функциите со исто име освен првата, преведувачот ја толкува декларацијата на следниов начин:

1.       Ако листите на аргументи се разликуваат по типот или по бројот на параметри , функциите се преклопени.

Example 1: Overloading Using Different Types of Parameter

#include <iostream>
using namespace std;
// function with float type parameter
float absolute(float var){
    if (var < 0.0)
        var = -var;
    return var;}
// function with int type parameter
int absolute(int var) {
     if (var < 0)
         var = -var;
    return var;}
int main() {
    // call function with int type parameter
    cout << "Absolute value of -5 = " << absolute(-5) << endl;
    // call function with float type parameter
    cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
    return 0;
}

Output

Absolute value of -5 = 5
Absolute value of 5.5 = 5.5

Example 2: Overloading Using Different Number of Parameters

#include <iostream>
using namespace std;
// function with 2 parameters
void display(int var1, double var2) {
    cout << "Integer number: " << var1;
    cout << " and double number: " << var2 << endl;}
// function with double type single parameter
void display(double var) {
    cout << "Double number: " << var << endl;}
// function with int type single parameter
void display(int var) {
    cout << "Integer number: " << var << endl;}
 
int main() {
    int a = 5;
    double b = 5.5;
    // call function with int type parameter
    display(a);
    // call function with double type parameter
    display(b);
    // call function with 2 parameters
    display(a, b);
    return 0;
}

Output

Integer number: 5
Float number: 5.5
Integer number: 5 and double number: 5.5


2. Ако типот на функциите и листите на аргументи се идентични, втората декларација ја
    смета за повторна декларација на функцијата.

       3. Ако листите на аргументи се идентични, а типот на функциите се различни, втората     декларација ја смета за погрешна декларација на функцијата и се јавува грешка.

Parameters should have a different type

add(int a, int b)
add(double a, double b)

#include <iostream>
using namespace std;
  
void add(int a, int b)
{
  cout << "sum = " << (a + b);}
 
void add(double a, double b)
{
    cout << endl << "sum = " << (a + b);}

int main()
{
    add(10, 2);
    add(5.3, 6.2);
     return 0;
}

Parameters should have a different number

add(int a, int b)
add(int a, int b, int c)

#include <iostream>
using namespace std;
 
void add(int a, int b)
{
  cout << "sum = " << (a + b);}
 
void add(int a, int b, int c)
{
    cout << endl << "sum = " << (a + b + c); }
 

// Driver code
int main()
{
    add(10, 2);
 
    add(5, 6, 4);
  
    return 0; } 

Parameters should have a different sequence of parameters

add(int a, double b)
add(double a, int b)

#include<iostream>
using namespace std;
void add(int a, double b)
{
cout<<"sum = "<<(a+b);
 

void  add(double a, int b)
{
cout<<endl<<"sum = "<<(a+b);

 
// Driver code
int main()
{
    add(10,2.5);
     add(5.5,6);
  
   return 0; } 
// CPP Program to demonstrate that function overloading
// fails if only return types are different
#include <iostream>
int fun() { return 10; }

char fun() { return 'a'; }
// compiler error as it is a new declaration of fun()

int main()
{
char x = fun();
return 0;
}

Output
 In function ‘char fun()’{ return 'a'; }
^
old declaration ‘int fun()’
int fun() { return 10; }
^

Резиме 

How the parameters list can be different?

Above are the signatures of the different ‘add’ functions. Now let us check which is valid or which is invalid.

  • int add(int, int) is valid, it is taking 2 ‘int’ type parameters and return ‘int’ value.
  • float add(float, float) is valid as it is taking 2 ‘float’ parameters and return the ‘float’ value. It is taking the same number of parameters but different data types as compared to the first one.
  • int add(int, int, int) is valid as it is taking 3 ‘int’ parameters and return ‘int’ value. It is taking a different number of parameters but has the same data types as compared to the first one.
  • float add(int, int) is invalid, it is the same as the first function which is both the function taking the same number of parameters and the same type of parameters. So, this is invalid. It doesn’t matter what type of data a function is returning. If two functions have the same number of parameters and of the same types then this is invalid.

No comments: