gpt4 book ai didi

c++ - 如果方法调用以两个冒号开头,这意味着什么?

转载 作者:可可西里 更新时间:2023-11-01 17:24:16 28 4
gpt4 key购买 nike

一位同事经常写这样的东西:

::someObject->someMethod(anAttribute, anotherAttribute);

someObject 是一个全局变量。
这两个冒号对我来说似乎很奇怪。没有它们,代码可以正常编译和运行。

同事声称这些冒号使 someObject 明确成为全局的,从而防止与可能的本地 someObject 混淆。我认为如果 someObject 已经在全局定义,您将无法在本地定义它?

您能否阐明这些冒号的含义以及它们是否必要?

最佳答案

您的同事是对的。您确实可以定义一个本地 someObject ,它将在该范围内隐藏全局 someObject :

SomeClass* someObject = ...;

// here the global object is visible
someObject->someMethod(anAttribute, anotherAttribute); // calls the global object

void someMethod() {
SomeClass* someObject = ...;
// here the local object hides the global
::someObject->someMethod(anAttribute, anotherAttribute); // calls the global object
someObject->someMethod(anAttribute, anotherAttribute); // calls the local object
}

// here again only the global object is visible
someObject->someMethod(anAttribute, anotherAttribute); // calls the global object

作用域可以递归地嵌入到其他作用域中,因此您可以在全局作用域中有一个命名空间,在命名空间中有一个类,在类中有一个内部类,在内部类中有一个方法,在方法中有一个 block ......等等。并且您可能在这些范围中的任何一个范围内具有相同名称的变量/类/方法/...。因此,识别特定名称所指的实体在 C++ 中并不是一项微不足道的任务。它被称为 name lookup .

简而言之,只要编译器找到一个名称,它就会从最内层的作用域开始查找该名称。 IE。在 someMethod 中,名称 someObject 与本地定义的对象相匹配。 ::someObject 覆盖此默认行为并使编译器仅在最外层(全局)范围内搜索,因此它找到全局对象而不是本地对象。

关于c++ - 如果方法调用以两个冒号开头,这意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3650263/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com