Peter Hwang Peter Hwang - 1 year ago 75
C++ Question

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.



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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download