Home >Backend Development >C++ >What is the symbol :: in c++?

What is the symbol :: in c++?

下次还敢
下次还敢Original
2024-04-26 17:09:151436browse

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.

What is the symbol :: in c++?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn