Home > Backend Development > C++ > body text

What does :: mean in c++

下次还敢
Release: 2024-04-28 20:03:16
Original
440 people have browsed it

The double colon (::) in C is mainly used for the following purposes: accessing elements in the global namespace. Access static members of a class. Specify the inheritance order in multiple inheritance. Casting.

What does :: mean in c++

Double colon (::) in C

In the C programming language, double colon (:: ) is a range resolution operator with the following uses:

  • #Accessing elements in the global namespace:
    If an element does not explicitly belong to namespace, you can use the :: operator to access declarations in its global namespace. For example:

    <code class="cpp">::std::cout << "Hello, world!"; // 输出 "Hello, world!" 到控制台</code>
    Copy after login
  • Accessing static members of a class:
    You can use the :: operator to access static members of a class (for example, static methods or static variables ) without creating an instance of the class. For example:

    <code class="cpp">class MyClass {
    public:
        static int myStaticVariable;
        static void myStaticMethod() {}
    };
    
    int main() {
        ::MyClass::myStaticVariable = 10; // 访问静态变量
        ::MyClass::myStaticMethod(); // 调用静态方法
    }</code>
    Copy after login
  • Specify the inheritance order in multiple inheritance:
    In multiple inheritance, you can use the :: operator to specify the inheritance order, especially It is when a subclass overrides a member of the base class with the same name. For example:

    <code class="cpp">class Base1 {
    public:
        void foo() { std::cout << "Base1::foo()\n"; }
    };
    
    class Base2 {
    public:
        void foo() { std::cout << "Base2::foo()\n"; }
    };
    
    class Derived : public Base1, public Base2 {
    public:
        void foo() { Base2::foo(); } // 指定从 Base2 继承 foo() 方法
    };</code>
    Copy after login
  • Forced type conversion:
    You can use the :: operator to force one type to another type, for example:

    <code class="cpp">int x = 10;
    double y = ::static_cast<double>(x); // 将 int x 转换为 double y</code>
    Copy after login

The above is the detailed content of What does :: mean in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c++
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!