什么是嵌套名称说明符?

新手上路,请多包涵

相关

我想知道嵌套名称说明符到底是什么?我查了草稿,但我可以理解语法,因为我还没有参加任何编译器设计课程。

 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;
}

原文由 Glenn 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 936
1 个回答

好问题!我学到了一些新的研究和实验。

你的评论是对的, ::S(); //Is ::S a nested name specifier <-- Yes, Indeed!

当您开始创建命名空间时,您会喜欢上它。变量可以在命名空间中具有相同的名称,而 :: 运算符是它们的区别。命名空间在某种意义上就像类,是另一层抽象。我不想让你厌烦命名空间。您可能不喜欢此示例中的嵌套名称说明符……考虑这个:

 #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;
}

请注意,我使用了 ::count 我可以简单地使用 count::count 指的是全局命名空间。

因此,在您的情况下,由于 S() 位于全局命名空间中(即,它在同一文件或包含的文件或任何未被 namespace <name_of_namespace> { } 封装的代码中声明,您可以使用 new struct ::Snew struct S ; 随你喜欢。

我刚刚了解到这一点,因为我很想回答这个问题,所以如果您有更具体和学过的答案,请分享:)

原文由 Igbanam 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题