几天前我提出了一个关于课堂内定义友元函数范围的问题(Which scope does an in-class-defined friend function belong to?),并且我知道该函数在封闭命名空间的范围内,但在类外显式声明之前不可搜索(ADL是一个例外)。
今天我在C++标准中找到了一些相关的说明(第11.3节):
今天我在C++标准中找到了一些相关的说明(第11.3节):
我们可以看到这里有两个与作用域相关的语句:"具有命名空间作用域" 和 "在定义它的类的 (词法) 作用域中"。我感到困惑。如果前者与我先前的问题有关 (一个在类内定义的友元函数属于哪个作用域?),那么后者代表什么?A function can be defined in a friend declaration of a class if and only if the class is a non-local class (9.8), the function name is unqualified, and the function has namespace scope. [ Example:
class M { friend void f() { } // definition of global f, a friend of M, // not the definition of a member function }; —end example ]
Such a function is implicitly
inline
. A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not (3.4.1).