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.
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:
::std::cout << "Hello, world!"; // 输出 "Hello, world!" 到控制台
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:
class MyClass { public: static int myStaticVariable; static void myStaticMethod() {} }; int main() { ::MyClass::myStaticVariable = 10; // 访问静态变量 ::MyClass::myStaticMethod(); // 调用静态方法 }
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:
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() 方法 };
Forced type conversion:
You can use the :: operator to force one type to another type, for example:
int x = 10; double y = ::static_cast(x); // 将 int x 转换为 double y
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!