cpp / beginner
Snippet
Typrückschluss mit dem auto-Schlüsselwort
Das auto-Schlüsselwort weist den Compiler an, den Variablentyp automatisch aus dem Initialisierer abzuleiten. Dies reduziert Boilerplate, wenn Typen langwierig sind, wie bei Standardbibliothek-Containern. Der Compiler weiß, dass 25 ein int, 19.99 ein double und "Charlie" ein std::string ist. Die Verwendung von auto verbessert die Lesbarkeit und reduziert Typfehler.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>#include <typeinfo>int main() {auto age = 25;auto price = 19.99;auto name = std::string("Charlie");auto initial = 'A';std::cout << "age is int: " << (typeid(age).name() == "i") << std::endl;std::cout << "price is double: " << (typeid(price).name() == "d") << std::endl;std::cout << "name is string: " << name << std::endl;std::cout << "initial is char: " << initial << std::endl;auto result = age + price;std::cout << "result type inferred from expression" << std::endl;return 0;}
Erklärung
1
auto age = 25;
Compiler leitet int aus dem Integer-Literal 25 ab
2
auto price = 19.99;
Compiler leitet double aus dem Fließkomma-Literal ab
3
auto name = std::string("Charlie");
Compiler sieht den expliziten std::string-Konstruktoraufruf
4
auto initial = 'A';
Compiler leitet char aus dem Zeichenliteral ab
5
auto result = age + price;
Typ wird aus dem Ergebnis des Ausdrucks abgeleitet (int + double = double)