gpt4 book ai didi

c++ - 为什么找到 f1 但找不到 f2?

转载 作者:行者123 更新时间:2023-11-30 02:36:23 28 4
gpt4 key购买 nike

以下代码在两个源文件中。

首先:

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;
}
}

第一段代码是从 C++ primer 复制的,唯一的区别是 C++ primer 调用 f2() 时没有命名空间前缀。第二 block 是我的补充。我现在想知道 f1f2 隐含地是命名空间 A 的成员,为什么 A::f2() 仍然是错误的而 f1(obj)可以通过ADL找到吗?

最佳答案

这是在 7.3.1.2 中找到的导致 A::f2() 失败的规则:

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. The friend declaration does not by itself make the name visible to unqualified lookup (3.4.1) or qualified lookup (3.4.3).

关于c++ - 为什么找到 f1 但找不到 f2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32815210/

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