简体   繁体   English

范围解析运算符的评估

[英]The evaluation of a scope resolution operator

This may be a stupid question. 这可能是一个愚蠢的问题。
I notice that we use scope resolution operator :: for both a namespace and a static member function. 我注意到我们将作用域解析运算符::用于名称空间和静态成员函数。

1) std::printf("foo"); 1) std::printf("foo");

2) MyClass::foo(); 2) MyClass::foo();

Here are my questions: 这是我的问题:
1. How could a C++ compiler differentiate them? 1. C ++编译器如何区分它们?
2. What is the process of a C++ compiler when it sees a scope resolution operator? 2. C ++编译器看到作用域解析运算符时,其处理过程是什么?

The gory details are in 3.4.3 Qualified name lookup of the C++ spec (with 3.3.1 Declarative regions and scopes and 5.1.1 (Primary expressions) General also providing some useful information.) 详细信息在C ++规范的3.4.3合格名称查找中(带有3.3.1声明性区域和范围以及5.1.1(主表达式)常规也提供了一些有用的信息。)

To boil it down, though, both namespaces and classes are "declarative regions", so in your example, std::cout refers to the name cout in the declarative region named std , and MyClass::foo refers to the name foo in the declarative region named MyClass . 归根结底,尽管名称空间和类都是“声明性区域”,所以在您的示例中, std::cout引用了声明性区域std的名称cout ,而MyClass::foo引用了声明性区域中的名称foo 。名为MyClass声明性区域。 As far as the :: operator is concerned, namespaces and classes are the "same sort of thing". ::操作符而言,名称空间和类是“同一种东西”。

In addition, because names must be unique within a declarative region (including the global namespace), the following code is invalid: 此外,由于名称在声明性区域(包括全局名称空间)内必须唯一,因此以下代码无效:

//invalid code - does not compile
namespace test { int x; }
class test { static int x; };

In other words, there is no ambiguity between test::x referring to the x in the namespace or the x in the class. 换句话说,在test::x引用命名空间中的x或类中的x之间没有歧义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM