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

The difference between :: and . in c++

下次还敢
下次还敢Original
2024-04-26 15:15:21914browse

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 . in c++

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 (::)

  • is used to access objects defined in the global namespace Identifier, variable, or function, for example: std::cout.
  • Used to access static members of a class (that is, members that do not depend on object instances), for example: ClassName::staticMember.
  • is used to qualify the class name to avoid name conflicts, for example: namespaceA::ClassName.

Period (.)

  • is used to access instance members of a class (that is, members associated with specific object instances), for example: object.instanceMember.
  • Used to call member functions of a class, for example: object.memberFunction().
  • is used to access the member pointed to by the object pointer or reference, for example: *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!

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