简体   繁体   中英

Can the :: operator appear in the context different from scope resolution in qualified name lookup?

As known scope resolution operator used for the purposes of qualified name lookup. But what is the value returned by :: ? As I understood it is postfix unary operator. Consider the following:

namespace A
{
    //something
}

A:: //error: expected unqualified-id before ‘int’

int main(){ }

Can you explain that behavior?

The scope resolution operator :: is only a syntatic operator, has no other semantics. That is, there are operators that only contribute to the syntax of the language, and others that contribute to the semantics/runtime behaviour of the program too, and that semantics could be customized. Thats operators overloading.

As far as I know the only meaning of the (not overloaded) :: operator is scope resolution. Your code is interpreted as A::int main() which generates the error.

The :: scope resolution operator is only used as, well... scope resolution operator.

Specifically the C++ grammar, as specified by the standard at §5.1.1/8, is:

qualified-id:
    nested-name-specifier template(opt) unqualified-id 
nested-name-specifier:
    ::
    type-name ::
    namespace-name ::
    decltype-specifier ::
    nested-name-specifier identifier ::
    nested-name-specifier templateopt simple-template-id ::

In your case nested-name-specifier is in the form of namespace-name :: , specifically A :: . For a qualified-id you need at least and unqualified-id .

An unqualified-id has the following grammar, as per §5.1.1:

unqualified-id:
    identifier 
    operator-function-id 
    conversion-function-id 
    literal-operator-id
    ~ class-name
    ~ decltype-specifier template-id

The scope resolution operator :: is not a function call, it is built in the language and it is used by the compiler to look up names, it will return the type that is find at its right.

Excerpt from the standard:

A nested-name-specifier that denotes a class, optionally followed by the keyword template (14.2), and then followed by the name of a member of either that class (9.2) or one of its base classes (Clause 10), is a qualified-id; 3.4.3.1 describes name lookup for class members that appear in qualified-ids. The result is the member. The type of the result is the type of the member.

In your case the compiler is looking up A::int which is obviously not what you'd like.

A simple example:

int count = 0;

int main(void) {
  int count = 0;
  ::count = 1;  // set global count to 1
  count = 2;    // set local count to 2
  return 0;
}

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