- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
如何在 friend 的函数体内对 using 名称执行非限定名称查找?让我们考虑以下代码:
#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
声明放在 friend 的函数定义之后,希望它不会被发现。 friend 不合格姓名查找的实际规则是什么?
最佳答案
答案很简单:
N4296::3.4.1/8 [basic.lookup.unqual]
:
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) — 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]
:
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.
就是这样。
更新:
内联在这里很重要。这就是为什么在类定义之外定义的友元函数不能直接使用类的静态成员。例如,下面的代码会报编译时错误:
#include <iostream>
class A
{
static int a;
friend void foo();
};
int A::a = 10;
void foo(){ std::cout << a << std::endl; }
int main(){ foo(); }
关于c++ - 友元函数和静态数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29574616/
我是一名优秀的程序员,十分优秀!