Home  >  Article  >  Backend Development  >  The difference between :: and . in c++

The difference between :: and . in c++

下次还敢
下次还敢Original
2024-04-26 15:39:131005browse

The difference between :: and . in C

Answer:
The :: and . in C are two different operators. Use For accessing class members and global members.

Detailed explanation:

1. :: (scope parsing operator)

  • is used to access the global Members, including variables, functions and types declared outside the class.
  • can be used to resolve naming conflicts, such as when the class name is the same as the global variable name.
  • Syntax: :: member name;

2. . (member access operator)

  • is used to access classes Members, including data members and member functions.
  • Must be used to access members from class instances.
  • Syntax: Object.Member name;

Difference:

  • Access scope::: Access global members, .Access class members.
  • Naming conflict: :: Can resolve naming conflict, . cannot.
  • Instance dependency: . Must be used to access members from class instances, :: is not required.

Example:

Access global variables:

<code class="cpp">int global_var = 10;
cout << ::global_var; //输出 10</code>

Access class data members:

<code class="cpp">class MyClass {
public:
    int data_member = 20;
};

MyClass object;
cout << object.data_member; //输出 20</code>

Resolving naming conflicts:

<code class="cpp">class MyClass {
public:
    static int global_var = 30;
};

int global_var = 40;
cout << ::MyClass::global_var; //输出 30</code>

The above is the detailed content of The difference between :: and . 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