friend functions of a class inside a namespace

后端 未结 3 1667
别那么骄傲
别那么骄傲 2021-01-18 16:50

I\'ve two question about this code bellow:

namespace A { class window; }

void f(A::window);

namespace A
{
    class window
    {
    private:
       int a;         


        
3条回答
  •  伪装坚强ぢ
    2021-01-18 17:53

    When you declare f() as a friend it's actually done in the enclosing namespace of the containing class (A in this case) if a forward declaration is not already present.

    So this...

    namespace A
    {
        class window
        {
        private:
            friend void ::f(window);
        };
    }
    

    essentially becomes this...

    namespace A
    {
        class window;
        void f(window);
    
        class window
        {
        private:
            friend void f(window);
        };
    }
    

    Edit: Here is a snippet from the C++ standard that explicltly talks about this scenario:

    Standard 7.3.1.2 / 3 :

    Every name first declared in a namespace is a member of that namespace. If a friend declaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup (3.4.1) or by qualified lookup (3.4.3) until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship).

提交回复
热议问题