Überladung bei Funktionen

Überladung ist ein Möglichkeit eine Funktion für unterschiedliche Parameter zu definieren. Am besten erstmal ein kleines Beispiel:

    #include<iostream>
    using namespace std;

    int max(int, int);
    int max(int, int, int);

    double max(double, double);
    double max(double, double, double);

    int main()
    {
      {
        int a=3;
        int b=4;
        int c=7;

        cout<<max(a,b)<<"\n";
        cout<<max(a,b,c)<<"\n";
      }

      {
        double a=5.46;
        double b=9.672;
        double c=3.223;

        cout<<max(a,b)<<"\n";
        cout<<max(a,b,c)<<"\n";
      }
    }

    int max(int a, int b)
    {
      if(a<b)
        return b;
      else
        return a;
    }

    int max(int a, int b, int c)
    {
      if(a<b)
        return max(b,c);
      else
        return max(a,c);
    }

    double max(double a, double b)
    {
      if(a<b)
        return b;
      else
        return a;
    }

    double max(double a, double b, double c)
    {
      if(a<b)
        return max(b,c);
      else
        return max(a,c);
    }

Wir haben max() einmal für 2 int und einmal für 3 int definiert: man kann also die Anzahl der Parameter variieren. Weiters haben wir noch double eingeführt - man kann also auch für bestimmte Typen überladen.

Überladung ist dafür da, dass man leicht unterschiedliche Funktionen gleich nennen kann. Es ist natürlich möglich ein max_int2() und max_int3() sowie max_double2() und max_double3() anzubieten - aber da ist max() doch viel schöner (und lesbarer).

Deine Aufgabe ist nun, eine Funktion kleiner(a,b) zu schreiben, welche true zurückgibt, wenn a kleiner b ist und false wenn das nicht der Fall ist. Danach überladest du diese Funktion für 3 und 4 int Parameter. Es soll dann gelten a<b<c.

Hier ist die Lösung

top