No cache version.

Caching disabled. Default setting for this page:enabled (code LNG204)
If the display is too slow, you can disable the user mode to view the cached version.

Surcharger des fonctions

Le C++ nous permet de travailler avec des fonctions qui portent le même nom, mais qui exécutent des opérations différentes. Au moment de la compilation, le compilateur détermine la fonction à appeler en fonction du nombre et du type d'arguments que la fonction appelle.

Le programme surcharge_somme.cpp nous fournit deux fonctions nommées "somme" qui retournent la somme des éléments d'un tableau.
Suivant le fait que la fonction main appelle la fonction somme en lui fournissant des entiers ou des flotants, une des deux fonctions somme sera appelée.

  1. #include <iostream.h>
  2.  
  3. int somme (int *tableau, int kMax)//kMax:nbre max de val du tableau
  4. {
  5. int r=0;//résultat
  6. int k;//compteur
  7. for (k=0;k<kMax;k++)
  8. r+=tableau[k];
  9. return(r);
  10. }
  11.  
  12. float somme (float *tableau, int kMax)
  13. {
  14. float r=0;
  15. int k;
  16. for (k=0;k<kMax;k++)
  17. r+=tableau[k];
  18. return(r);
  19. }
  20.  
  21. void main (void)
  22. {
  23. int i[9]={1,2,3,4,5,6,7,8,9};
  24. float f[4]={1.1,2.2,3.3,4.4};
  25. cout << "Somme des entiers: " << somme(i,9) << '\n';
  26. cout << "Somme des flotants: " << somme(f,4) << '\n';
  27. }

Autre exemple: le programme swap permet d'intervertir deux ou quatre valeurs suivant le nombre d'arguments passés à la fonction swap.

  1. #include <iostream.h>
  2.  
  3. void swap (int *a, int *b)
  4. {
  5. int temp=*a;
  6. *a=*b;
  7. *b=temp;
  8. }
  9.  
  10. void swap (int *a, int *b, int *c, int *d)
  11. {
  12. int temp=*a;
  13. *a=*b;
  14. *b=temp;
  15. temp=*c;
  16. *c=*d;
  17. *d=temp
  18. }
  19.  
  20. void main (void)
  21. {
  22. int a=1,b=2,c=3,d=4;
  23. swap(&a, &b);
  24. cout << "Echange des 2 valeurs: " << a << b << '\n';
  25. swap(&a, &b, &c, &d);
  26. cout << "Echange des 4 valeurs: " << a << b << c << d << '\n';
  27. }

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 24/12/2002, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/cp-surcharge.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.