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

The difference between :: and : in c++

下次还敢
下次还敢Original
2024-04-26 17:57:15954browse

Double colon (::) is used for namespace scope resolution and class static member access, and single colon (:) is used for base class initialization and implicit type conversion.

The difference between :: and : in c++

The difference between :: and : in C

In the C programming language, double colon ( The ::) and single colon (:) operators have different usage and meaning.

Double colon(::)

Double colon(::) The operator is used in the following scenarios:

  • Namespace scope resolution: Used when accessing elements in external namespaces in nested namespaces. For example:
<code class="cpp">namespace outer {
  int x = 10;
}

namespace inner {
  void printX() {
    std::cout << outer::x << std::endl;
  }
}</code>
  • Class static member access: Used when accessing static member functions or variables of a class. For example:
<code class="cpp">class MyClass {
public:
  static int numInstances = 0;
  
  static void printNumInstances() {
    std::cout << numInstances << std::endl;
  }
};</code>

Single colon(:)

Single colon(:) The operator is used in the following scenarios:

  • Base class initialization: Used when initializing base class members in the derived class constructor. For example:
<code class="cpp">class Base {
public:
  int x;
};

class Derived : public Base {
public:
  Derived(int x) : x(x) {}
};</code>
  • Implicit type conversion: Used when coercing a value of one type to another type. For example:
<code class="cpp">int x = 10;
double y = static_cast<double>(x);</code>

Summary

Double colon (::) is used for namespace scope resolution and class static member access, while single colon (:) Used for base class initialization and implicit type conversion.

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
Previous article:How to use counter in c++Next article:How to use counter in c++