Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么找到f1而没有找到f2?_C++_Friend Function - Fatal编程技术网

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