C++ 为什么找到f1而没有找到f2?
以下代码位于两个源文件中 第一:C++ 为什么找到f1而没有找到f2?,c++,friend-function,C++,Friend Function,以下代码位于两个源文件中 第一: namespace A { // two friends; neither is declared apart from a friend declaration // these functions implicitly are members of namespace A class C { friend void f2(); // won’t be found, unless otherwise
namespace A {
// two friends; neither is declared apart from a friend declaration
// these functions implicitly are members of namespace A
class C {
friend void f2(); // won’t be found, unless otherwise declared
friend void f1(const C&); // found by argument-dependent lookup
};
}
int main()
{
A::C obj;
f1(obj); // ok: find A::f through the friend declaration in A::C
A::f2(); // no member named f2 in namespace A
}
第二点:
#include <iostream>
namespace A {
class C;
void f1(const C&) {
std::cout << 1;
}
void f2() {
std::cout << 2;
}
}
#包括
名称空间A{
丙级;;
无效f1(常数C&){
std::cout在第一个代码块中,f2
在A::C
的词法范围内,即名称在A::C
的范围内可见。它在A::C
之外不可见
要使f2
在A::C
的范围之外可见,您需要在A
中声明或定义它,这是在7.3.1.2中找到的导致A::f2()
失败的规则:
如果非本地类中的友元声明首先声明类、函数、类模板或函数模板,则友元是最内部封闭命名空间的成员。友元声明本身不会使名称对非限定查找(3.4.1)或限定查找(3.4.3)可见
我第一次遇到ADL…我的反应大概是“OHMYGODWHY”.@Cubic以至于std::难道我还不明白为什么f1是由ADL找到的,而f2不是吗?它们之间有什么区别吗?或者,从你摘录的最后一句话来看,仅仅因为f1是由ADL找到的?@xlnwel:是的,ADL规则允许查找无法通过名称找到的东西。f1
是由ADL找到的。因为f2
没有任何名称参数,ADL不能用于查找f2
。