朋友功能和静态数据成员

朋友功能和静态数据成员

本文介绍了朋友功能和静态数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在好友的函数体内对姓名进行不合格的姓名查找?让我们考虑以下代码:

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]中的标准状态:

因此,我希望没有不合格的名称查找会找到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]:

[...]

(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]:

就是这样.

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

这篇关于朋友功能和静态数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 18:04