Can class members be defined outside the namespace in which they are declared?

六月ゝ 毕业季﹏ 提交于 2019-12-01 03:11:54

Yes, the syntax is indeed legal, but no, your function actually does live in the namespace NS. The code you are seeing is actually equivalent to

namespace NS { void C::f() { /* ... } }

or to

void NS::C::f() { /* ... */ }

which may be more similiar to what you are used to.

Because of the using-directive you can omit the NS part not only in calling code, but also in its definition. The Standard has an example that matches your code (after the bold emphasized part):

3.4.3.2 Namespace members [namespace.qual]

7 In a declaration for a namespace member in which the declarator-id is a qualified-id, given that the qualified-id for the namespace member has the form nested-name-specifier unqualified-id the unqualified-id shall name a member of the namespace designated by the nested-name-specifier or of an element of the inline namespace set (7.3.1) of that namespace. [ Example:

namespace A {
  namespace B {
    void f1(int);
  }
  using namespace B;
}
void A::f1(int){ } // ill-formed, f1 is not a member of A

—end example ] However, in such namespace member declarations, the nested-name-specifier may rely on using-directives to implicitly provide the initial part of the nested-name-specifier. [ Example:

namespace A {
  namespace B {
    void f1(int);
  }
}

namespace C {
  namespace D {
    void f1(int);
  }
}

using namespace A;
using namespace C::D;
void B::f1(int){ } // OK, defines A::B::f1(int)

—end example ]

So you may omit the initial part of the nested-name-specifier, but not any intermediate part.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!