friend functions of a class inside a namespace

落爺英雄遲暮 提交于 2019-12-01 17:08:02

问题


I've two question about this code bellow:

namespace A { class window; }

void f(A::window);

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

void f(A::window rhs)
{
    std::cout << rhs.a << std::endl;
}

1) why do I need to qualify the member function f inside window class to be global by doing ::f(window) ?

2) why do I need to predeclare the function f(A::window) in this particular case, whereas when the class is not defined inside a namespace it's ok for the function to be declared after the function is declared a friend.


回答1:


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).




回答2:


As for 1), your function is not in the namespace, so you must use :: to tell the compiler to search it outside the namespace.

Otherwise, it will only look for function inside the namespace (that's why they exist). Koenig lookup doesn't apply here, as window class is inside the namespace.

not too sure about 2) though, but i bet it is related to 1).




回答3:


1) because function f is declared and defined outside of the current namespace. If you moved the definition of your class into the same namespace as the function whether global or otherwise you wouldn't need to.

2) you always need to declare a function before it is referenced. Your class references the function with the friend statement.



来源:https://stackoverflow.com/questions/10937096/friend-functions-of-a-class-inside-a-namespace

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