Home >Backend Development >C++ >What is the symbol :: in c++?
The :: symbol in C is the scope operator used to resolve name conflicts and access identifiers in other scopes, including: Accessing global variables: Access global variables by prefixing the namespace name. Access class members: Access class member variables or static member functions by prefixing the class name. Access member functions outside the class: Allows use of member functions from outside the class. Access template class methods: Access template class methods for a specific instantiation.
The ::symbol in C
In the C programming language, :: The symbol represents the scope operator, which is used to access identifiers within nested scopes.
Role
:: Symbol is used to resolve name conflicts and access identifiers in other scopes.
Usage
Access global variables:
<code class="cpp">namespace my_namespace { int my_var; } int main() { ::my_namespace::my_var = 10; }</code>
In this example, ::my_namespace ::my_var allows access to my_var variables defined in the my_namespace namespace from the main function.
Access class members:
<code class="cpp">class MyClass { public: static int my_class_var; }; int main() { ::MyClass::my_class_var = 20; }</code>
Here, ::MyClass::my_class_var allows access to the static member variable my_class_var of the MyClass class from the main function .
Accessing member functions outside the class:
<code class="cpp">class MyClass { void my_member_function(); }; void MyClass::my_member_function() { ::cout << "Hello World!" << endl; }</code>
By using ::, you can access the member functions of a class from outside the class.
Methods to access the template class:
<code class="cpp">template <typename T> class MyTemplate { public: static void my_method(); }; void MyTemplate<int>::my_method() { ::cout << "This is an int template!" << endl; }</code>
Using the :: notation, you can access the methods of a specific instantiation of the template class.
The above is the detailed content of What is the symbol :: in c++?. For more information, please follow other related articles on the PHP Chinese website!