Home > Article > Backend Development > The difference between :: and . in c++
The colon (::) is used to access the global namespace or static members of the class, while the period (.) is used to access the instance members of the class. For example, std::cout uses :: to access functions in the global namespace, and obj.instanceVar uses . to access instance member variables of a class.
The difference between:: and .
Short answer:
Colon (::) is used to access the global namespace or static members of the class, while period (.) is used to access instance members of the class.
Detailed answer:
Colon (::)
std::cout
. ClassName::staticMember
. namespaceA::ClassName
. Period (.)
object.instanceMember
. object.memberFunction()
. *objectPtr.member
. Example:
<code class="cpp">// 全局命名空间的函数 std::cout << "Hello world!" << std::endl; // 类的静态成员变量 class MyClass { public: static int staticVar; }; int MyClass::staticVar = 42; // 类的实例成员变量和函数 class MyObject { public: int instanceVar; void instanceFunc() { std::cout << instanceVar << std::endl; } }; MyObject obj; obj.instanceVar = 10; obj.instanceFunc(); // 输出: 10</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!