cpp / beginner
Snippet
Namespaces: Namenskonflikte vermeiden
Namespaces organisieren Code in benannte Gruppen, um Namenskonflikte zu vermeiden. Derselbe Bezeichner kann in verschiedenen Namespaces existieren, ohne Kollision. Verwenden Sie den Bereichsauflösungsoperator (::), um auf Namespace-Mitglieder zuzugreifen. Der std-Namespace enthält Standardbibliothekskomponenten.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>namespace math {int multiply(int a, int b) {return a * b;}}namespace text {int multiply = 5;}int main() {std::cout << "math::multiply(4, 3) = " << math::multiply(4, 3) << std::endl;std::cout << "text::multiply = " << text::multiply << std::endl;return 0;}
Erklärung
1
namespace math { }
Definiert einen Namespace namens 'math'
2
namespace text { }
Definiert einen separaten Namespace namens 'text'
3
math::multiply(4, 3)
Greift auf multiply-Funktion aus math-Namespace zu
4
text::multiply
Greift auf multiply-Variable aus text-Namespace zu