朋友功能在班级中不可见 [英] Friend function is not visible in the class
问题描述
我有以下代码:
struct M {
friend void f() {}
M() {
f(); // error: 'f' was not declared in this scope
}
};
int main() {
M m;
}
g ++ 4.8和clang3.4均无法编译,因为 f
在 M
内部不可见,或者这样说。
Both g++4.8 and clang3.4 fail to compile it, because f
is not visible inside M
, or so they say.
但是,该标准给出了类似代码的示例
However, the Standard gives an example of a similar code
class M {
friend void f() { } // definition of global f, a friend of M,
// not the definition of a member function
};
并说
在一个类中定义的
friend
函数在定义它的
类的(词法)范围内。
A
friend
function defined in a class is in the (lexical) scope of the class in which it is defined.
(ISO / IEC 14882:2011 11.3 Friends [class.friend] p6,p7)
(ISO/IEC 14882:2011 11.3 Friends [class.friend] p6, p7)
由此我无法理解编译器如何找不到 f
,它是在使用它的同一类中定义的。
From this I can't understand how compiler can't find f
which is defined in same class where it's used.
这两个编译器都有相同的错误是不太可能的。
那么,我错过了什么?
It's kinda unlikely that both compilers have the same bug.
So, what did I miss?
推荐答案
friend声明指出,周围名称空间中的名为 f
的函数是该类的朋友;但不会在名称空间中引入名称 f
。除非在命名空间中声明了它,否则它不可用(除非依赖于参数的查找)。
The friend declaration states that a function called f
in the surrounding namespace is a friend of the class; but it does not introduce the name f
into the namespace. It's not available (except by argument-dependent lookup) until it's been declared in the namespace.
相关规则是C ++ 11 7.3.1.2/3:
The relevant rule is C++11 7.3.1.2/3:
如果非本地类中的
friend
声明首先声明了一个类或函数,朋友类或函数是最内部的封闭名称空间的成员。 通过无限定查找或限定查找无法找到朋友的名字,直到在该命名空间范围内提供匹配的声明为止。
If a
friend
declaration in a non-local 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 or by qualified lookup until a matching declaration is provided in that namespace scope.
这篇关于朋友功能在班级中不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!