朋友功能和静态数据成员 [英] Friend functions and static data members
问题描述
如何在好友的函数体内对姓名进行不合格的姓名查找?让我们考虑以下代码:
How is unqualified name lookup being performed for names using within the friend's function body? Let's consider the following code:
#include <iostream>
void foo();
class A
{
friend void foo(){ std::cout << a << std::endl; }
static int a;
};
int A::a = 10;
int main(){ foo(); }
N4296::7.3.1.2/3 [namespace.memdef]
中的标准状态:
如果非本地类中的朋友声明首先声明了一个类, 朋友是成员的函数,类模板或函数模板 最内层的封闭命名空间.
If a friend declaration in a non-local class first declares a class, function, class template or function template the friend is a member of the innermost enclosing namespace.
因此,我希望没有不合格的名称查找会找到A::a
,但确实如此.我特意将A::a
声明放在朋友的函数定义之后,希望找不到该声明.朋友不合格姓名查找的实际规则是什么?
So, I expected unqualified name lookup didn't find A::a
, but it did. I deliberately put the A::a
declaration after the friend's function definition in hope it wouldn't be found. What's the actual rule for the friend's unqualified name lookup?
推荐答案
答案很简单:
N4296::3.4.1/8 [basic.lookup.unqual]
:
对于类X的成员,成员函数中使用的名称 正文 ,在默认参数中,在例外规范中, 非静态数据成员的括号或相等初始化器(9.2),或 X的定义之外的类成员的定义, 在成员的声明者ID31之后,应在以下任一者中声明 可以通过以下方式:
For the members of a class X, a name used in a member function body, in a default argument, in an exceptionspecification, in the brace-or-equal-initializer of a non-static data member (9.2), or in the definition of a class member outside of the definition of X, following the member’s declarator-id31, shall be declared in one of the following ways:
[...]
(8.2)—应该是X类的成员或是X的基类的成员 X(10.2),
(8.2) — shall be a member of class X or be a member of a base class of X (10.2),
[...]
N4296::3.4.1/9 [basic.lookup.unqual]
:
在 朋友功能 的定义中使用的名称的名称查找 (11.3)在授予友谊的课程中,应进行 定义的内联 如成员函数定义中的 查找 所述.
Name lookup for a name used in the definition of a friend function (11.3) defined inline in the class granting friendship shall proceed as described for lookup in member function definitions.
就是这样.
UPD:
内联 在这里很重要.这就是为什么在类定义之外定义的friend函数不能直接使用类的静态成员的原因.例如,以下代码会引发编译时错误:
Inlining is important here. That's why the friend function defined outside the class defintion cannot use static members of the class directly. For instance, the following code pritns compile-time error:
#include <iostream>
class A
{
static int a;
friend void foo();
};
int A::a = 10;
void foo(){ std::cout << a << std::endl; }
int main(){ foo(); }
DEMO
这篇关于朋友功能和静态数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!