关于此代码,我有两个问题:
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)为什么我需要通过:: f(window)将窗口类内部的成员函数f限定为全局变量?
1) why do I need to qualify the member function f inside window class to be global by doing ::f(window) ?
2)为什么在这种特殊情况下我需要预先声明函数f(A :: 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.
推荐答案如果将f()声明为好友,则实际上是在包含类的封闭名称空间(在本例中为A)中完成的,如果前向声明为还不存在.
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.
所以这个...
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); }; }以下是C ++标准的摘要,明确讨论了这种情况:
Here is a snippet from the C++ standard that explicltly talks about this scenario:
标准7.3.1.2/3:
Standard 7.3.1.2 / 3 :
首先在名称空间中声明的每个名称都是该名称空间的成员. 如果非本地类中的朋友声明首先声明了一个类或函数,则该朋友类或函数是最内层的封闭命名空间的成员.通过不合格的查找找不到朋友的名称(3.4.1) )或通过合格查找(3.4.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).
更多推荐
命名空间中的类的朋友功能
发布评论