gpt4 book ai didi

C++ 找不到命名空间外的函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:49:52 24 4
gpt4 key购买 nike

编译以下代码失败,因为第二个函数找不到第一个函数,即使它在命名空间之外。我自己无法弄清楚问题所在,到目前为止我还没有在网上找到任何答案。

测试.cpp:

#include <bits/stdc++.h>

struct myclass {};

template <typename T, typename U>
std::ostream& operator<< (std::ostream &os, const std::pair<T, U> &p) {
os << "(" << p.first << ", " << p.second << ")";
return os;
}

namespace my {
void operator<< (std::ostream os, myclass m) {
std::cout << std::pair<int, int>(5, 4); // This is line 13.
}
}

int main() {
return 0;
}

编译器给出的错误(g++ test.cpp -O2 -o test.exe):
test.cpp:13:13: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::pair<int, int>') .
它继续,给出一长串关于什么的建议 operator<<可能意味着。

观察 1:如果两个函数的名称不同,则不会发生错误。
观察 2:如果 namespace my { }被删除,不会发生错误。

最佳答案

这是一种名字隐藏;不能通过不同的作用域重载函数/运算符。

根据name lookup的规则,

(强调我的)

..., name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.

对于这种情况,名称 operator<<在命名空间 my 的范围内找到(即它自己),然后停止名称查找,不会检查全局范围,全局 operator<<不会考虑以下重载决议。

Observation 1: If the two functions differ in name, no error occurs.

这很好,因为没有隐藏名字。

Observation 2: If namespace my { } is removed, no error occurs.

这很好,因为两个 operator<<被放在相同的范围内,即全局命名空间。然后都是operator<<可以找到然后在重载决议中考虑,最后选择合适的。

如评论提示,可以申请using将全局命名空间中的名称引入命名空间my ;然后都是operator<<将被发现,然后在重载决议中予以考虑。

关于C++ 找不到命名空间外的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54829319/

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