简体   繁体   中英

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");

2) MyClass::foo();

Here are my questions:
1. How could a C++ compiler differentiate them?
2. What is the process of a C++ compiler when it sees a scope resolution operator?

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.)

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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