Is this valid C++ code?

后端 未结 4 799
迷失自我
迷失自我 2021-02-04 00:37

I had the following code, which was basically,

class foo {
  public:
    void method();
};

void foo::foo::method() { }

I had accidentally adde

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 01:30

    Krugar has the correct answer here. The name that is is being found each time is the injected class name.

    The following is an example which shows at least one reason why the compiler adds the injected class name:

    namespace NS
    {
      class B
      {
      // injected name B    // #1
      public:
        void foo ();
      };
    
      int i;                // #2
    }
    
    class B                 // #3
    {
    public:
      void foo ();
    };
    
    
    int i;                  // #4
    
    class A :: NS::B
    {
    public:
      void bar ()
      {
        ++i;           // Lookup for 'i' searches scope of
                       // 'A', then in base 'NS::B' and
                       // finally in '::'.  Finds #4
    
        B & b = *this; // Lookup for 'B' searches scope of 'A'
                       // then in base 'NS::B' and finds #1
                       // the injected name 'B'.
    
      }
    };
    

    Without the injected name the current lookup rules would eventually reach the enclosing scope of 'A' and would find '::B' and not 'NS::B'. We would therefore need to use "NS::B" everywhere in A when we wanted to refer to the base class.

    Another place that injected names get used are with templates, where inside the class template, the injected name provides a mapping between the template name and the type:

    template 
    class A
    {
    // First injected name 'A'
    // Additional injected name 'A' maps to 'A'
    
    public:
      void foo ()
      {
        // '::A' here is the template name
        // 'A' is the type 'A'
        // 'A' is also the type 'A'
      }
    };
    

提交回复
热议问题