我试图像这样在名称空间之外定义类朋友函数:
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),而当在命名空间中未定义类时,在将函数声明为a之后对函数进行声明是可以的朋友.
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!
更多推荐
命名空间中的类朋友功能
发布评论