cpp / beginner
Snippet
Funktionsüberladung
Funktionsüberladung ermöglicht mehrere Funktionen mit demselben Namen, aber unterschiedlichen Parametertypen. Der Compiler bestimmt, welche Funktion aufgerufen wird, basierend auf den übergebenen Argumenten. Dies macht Code lesbarer, indemdeskriptive Namen für ähnliche Operationen auf verschiedenen Datentypen verwendet werden.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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 Parameter
2
double add(double a, double b)
Zweite Überladung für Fließkommaparameter
3
std::string add(std::string a, std::string b)
Dritte Überladung für Zeichenkettenparameter
4
std::cout << add(5, 3) << std::endl;
Compiler wählt automatisch die int-Version