gpt4 book ai didi

c++ - 内联友元函数的范围是什么?

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

在搜索了 SO 之后,一个问题告诉我,内联友元函数的 词法 范围是它定义的类,这意味着它可以访问例如类中的 typedef 不限定它们。但后来我想知道这样一个函数的实际范围是什么? GCC 至少拒绝了我调用它的所有尝试。可以通过 ADL 以外的方式调用示例中的函数吗?由于没有参数,这在此处是不可能的?

感谢标准报价,因为我目前无法访问我的拷贝。

The following code

namespace foo{
struct bar{
friend void baz(){}
void call_friend();
};
}

int main(){
foo::baz(); // can't access through enclosing scope of the class
foo::bar::baz(); // can't access through class scope
}

namespace foo{
void bar::call_friend(){
baz(); // can't access through member function
}
}

导致这些错误:

prog.cpp: In function ‘int main()’:
prog.cpp:9: error: ‘baz’ is not a member of ‘foo’
prog.cpp:10: error: ‘baz’ is not a member of ‘foo::bar’
prog.cpp: In member function ‘void foo::bar::call_friend()’:
prog.cpp:15: error: ‘baz’ was not declared in this scope

最佳答案

当你在一个类中声明一个带有非限定 id 的 friend 函数时,它会在最近的封闭命名空间范围内命名一个函数。

如果该函数之前未声明过,则 friend 声明不会使该函数在该范围内可见以进行正常查找。它确实使声明的函数对依赖于参数的查找可见。

许多注释都强调了这一点,但最终声明在 7.3.1.2/3(ISO/IEC 14882:2011)中:

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 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 (3.4.1) or by qualified lookup (3.4.3) until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship). If a friend function 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.

关于c++ - 内联友元函数的范围是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8207633/

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