class friend function inside a namespace

懵懂的女人 提交于 2019-12-05 16:11:42

问题


Im trying to define a class friend function outside the namespace like this:

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

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

Im getting an error said that there is ambiguity. and there is two candidates void A::f(A::window); and void f(A::window). So my question is :

1) How to make the global function void f(A::window rhs) a friend of the class A::window.

EDIT: (After reading the answers)

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

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


回答1:


As well as adding a :: you need to forward declare it, e.g.:

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;
}

Note that for this forward declaration to work you need to forward declare the class too!




回答2:


This should do it: you need forward declares to make it clear f is in the global namespace (and not file static):

#include <string>
#include <iostream>

using namespace std;

////// forward declare magic:

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

//////

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

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

int main()
{
}


来源:https://stackoverflow.com/questions/10934226/class-friend-function-inside-a-namespace

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