简体   繁体   中英

Why is it not possible to define a fully-qualified function within a foreign namespace? May I know what the standard says?

Is this is wrong? Why? May I know what the standard says?

 namespace N{
  namespace N1{
     namespace N2{
        struct A{
         struct B{
          void fun();
       };//B
     }; //A
   } //n2
 }//n1
 namespace N3{
     void N1::N2::A::B::fun(){} //error
 }//n3
}//n

int main()
 {
  return 0;
 }

May I know why it is failing?

This is invalid due to §9.3/2:

A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition.

The scope of the namespace N3 does not enclose the definition of the class B

Here is a much simpler example, that also fails to compile:

namespace N1 { 
  void f() ;
}

namespace N2 {
  void N1::f() { }
}

To put the answer in plain English, the definition of a function or method which belongs to a class (or struct) needs to be in the same namespace as the class definition. In other words, you can't declare the function in one namespace and then define it in another.

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