Home > Backend Development > C++ > body text

The difference between :: and : in c++

下次还敢
Release: 2024-04-26 17:57:15
Original
953 people have browsed it

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>
Copy after login
  • 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>
Copy after login

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>
Copy after login
  • 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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template