命名空间内的类友元函数

2022-01-14 00:00:00 namespaces c++ friend

我试图在命名空间之外定义一个类友函数,如下所示:

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

我收到一个错误,说有歧义.并且有两个候选 void A::f(A::window);void f(A::window).所以我的问题是:

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) 如何使全局函数void f(A::window rhs)成为A::window类的朋友.

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

(阅读答案后)

2) 为什么我需要通过 ::f(window) 将窗口类中的成员函数 f 限定为全局?

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

3) 为什么在这种特殊情况下我需要预先声明函数 f(A::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.

推荐答案

除了添加 :: 还需要转发声明,例如:

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!

相关文章