capypad
0 Tage Serie
cpp / beginner
Snippet

Funktionsüberladung: Mehrere Funktionen mit demselben Namen

Funktionsüberladung ermöglicht mehrere Funktionen mit demselben Namen aber unterschiedlichen Parametertypen. Der Compiler bestimmt, welche Funktion aufgerufen wird, basierend auf den Argumenttypen. Dies bietet eine saubere Möglichkeit, Operationen zu definieren, die ähnlich über verschiedene Datentypen funktionieren.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 
int add(int a, int b) {
return a + b;
}
 
double add(double a, double b) {
return a + b;
}
 
std::string add(std::string a, std::string b) {
return a + b;
}
 
int main() {
std::cout << add(5, 3) << std::endl;
std::cout << add(2.5, 3.7) << std::endl;
std::cout << add(std::string("Hello "), std::string("World")) << std::endl;
return 0;
}
Erklärung
1
int add(int a, int b)
Erste Überladung für ganzzahlige Addition
2
double add(double a, double b)
Zweite Überladung für Gleitkomma-Addition
3
std::string add(...)
Dritte Überladung für String-Verkettung
4
add(5, 3)
Compiler wählt int-Version basierend auf ganzzahligen Argumenten