C++ 什么是嵌套名称说明符?
有关 我想知道嵌套名称说明符到底是什么?我查阅了草稿,但我能理解语法,因为我还没有参加任何编译器设计课程C++ 什么是嵌套名称说明符?,c++,names,C++,Names,有关 我想知道嵌套名称说明符到底是什么?我查阅了草稿,但我能理解语法,因为我还没有参加任何编译器设计课程 void S(){} struct S{ S(){cout << 1;} void f(){} static const int x = 0; }; int main(){ struct S *p = new struct ::S; p->::S::f(); S::x; ::S(); // Is ::S a ne
void S(){}
struct S{
S(){cout << 1;}
void f(){}
static const int x = 0;
};
int main(){
struct S *p = new struct ::S;
p->::S::f();
S::x;
::S(); // Is ::S a nested name specifier?
delete p;
}
void S(){}
结构{
S(){cout::S::f();
S::x;
::S();//::S是嵌套的名称说明符吗?
删除p;
}
::S
是一个合格的id
在限定id::S::f
中,S::
是嵌套的名称说明符
在非正式术语1中,嵌套的名称说明符是
- 在限定id的最开始处开始,或者在初始范围解析运算符(
)之后开始(如果在id的最开始处出现),并且:
- 以限定id中的最后一个作用域解析运算符结束
struct A {
struct B {
void F();
};
};
是一个非限定idA
是一个限定id,但没有嵌套的名称说明符::A
是一个限定id,A::B
是一个嵌套的名称说明符A::
是限定id,::A::B
是嵌套名称说明符A::
是一个限定id,A::B::F
和B:
都是嵌套的名称说明符A::B::
是一个限定id,::A::B::F
和B:
都是嵌套的名称说明符A::B::
[1] 这是一个相当不精确的描述。很难用简单的英语描述语法…嵌套的命名空间说明符是:
nested-name-specifier :
class-or-namespace-name::nested-name-specifier(optional)
也就是说,名称空间和类名的非空列表,每个名称后面紧跟着:,表示程序整体“名称空间树”中的相对分支。例如,my_名称空间:
,my_名称空间::Internal_名称空间:
,my_名称空间::my_类:
,以及my_类:
请特别注意与以下内容的区别:
qualified-namespace-specifier :
::(optional) nested-name-specifier(optional) class-or-namespace-name
因为嵌套的名称说明符可能不是绝对的(前缀为:
以引用全局范围),而限定的命名空间说明符可以是绝对的,但不能以:
结尾
在您的示例中,
::S
解析为函数::S()
,而不是结构(在问题开始时链接到的问题的Stackoverflow中讨论了该结构的前依存规则),所以它不是一个嵌套的名称说明符。好问题!我在研究和试验它时学到了一些新东西
你的评论是对的,
::S();//S::S是嵌套名称说明符我想得越多,就越觉得这不是一个很好的答案。我不知道如何用简单的术语解释它,但仍然是完全正确的……小Q:a::B
->我能说a
是限定结构,同时a:
是嵌套名称说明符吗?
#include <iostream>
using namespace std;
int count(0); // Used for iteration
class outer {
public:
static int count; // counts the number of outer classes
class inner {
public:
static int count; // counts the number of inner classes
};
};
int outer::count(42); // assume there are 42 outer classes
int outer::inner::count(32768); // assume there are 2^15 inner classes
// getting the hang of it?
int main() {
// how do we access these numbers?
//
// using "count = ?" is quite ambiguous since we don't explicitly know which
// count we are referring to.
//
// Nested name specifiers help us out here
cout << ::count << endl; // The iterator value
cout << outer::count << endl; // the number of outer classes instantiated
cout << outer::inner::count << endl; // the number of inner classes instantiated
return 0;
}