gpt4 book ai didi

c++ - 成员函数 Outer::f() 不是类 Outer::Inner 的 friend 。为什么?

转载 作者:IT老高 更新时间:2023-10-28 23:18:21 26 4
gpt4 key购买 nike

根据clang , gcc 和 vs2013,函数 Outer::fnotOuter::Inner 的 friend 。

struct Outer {
void f() {}
class Inner {
friend void f();
static const int i = 0;
};
};

void f() { int i = Outer::Inner::i; }

从 [namespace.memdef]/3 我希望函数 Outer::f 成为 Outer::Inner 的 friend ,而不是 : :f,因为 friend 声明不是其 namespace 中包含名称 f第一个

[namespace,memdef]/3(重点是我的):

Every name first declared in a namespace is a member of that namespace. If a friend declaration in a non-local class first declares a class, function, class template or function template97 the friend is a member of the innermost enclosing namespace. The friend declaration does not by itself make the name visible to unqualified lookup (3.4.1) or qualified lookup (3.4.3). [ Note: The name of the friend will be visible in its namespace if a matching declaration is provided at namespace scope (either before or after the class definition granting friendship). — end note ] If a friend function or function template is called, its name may be found by the name lookup that considers functions from namespaces and classes associated with the types of the function arguments (3.4.2). If the name in a friend declaration is neither qualified nor a template-id and the declaration is a function or an elaborated-type-specifier, the lookup to determine whether the entity has been previously declared shall not consider any scopes outside the innermost enclosing namespace.

最佳答案

您引用的标准的第一部分说(强调我的):

Every name first declared in a namespace is a member of that namespace. If a friend declaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace.

您假设一个类与命名空间相同,这是不正确的。

namespace Outer {
void f();
class Inner {
friend void f();
static const int i = 0;
};
}

void Outer::f() { int i = Outer::Inner::i; }

应该可以。要将类成员函数用作 friend ,您必须使用:

struct Outer {
void f();
class Inner {
friend void Outer::f();
static const int i = 0;
};
};

void Outer::f() { int i = Outer::Inner::i; }

关于c++ - 成员函数 Outer::f() 不是类 Outer::Inner 的 friend 。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31348475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com