为什么我可以使用 std 命名空间中的名称,即使我是 "using namespace std;"?
Why am I able to use the names in the std namespace even though I'm "using namespace std;"?
算法头文件中不是已经有max函数了吗?
通过 using namespace std;
,我将函数导入到全局命名空间(它接受参数,在本例中两者都是整数,因此它不应该是重载)。
那么为什么没有命名冲突呢?
#include <iostream>
#include <algorithm>
using namespace std;
int max(int a, int b)
{
return (a > b) ? a : b;
}
int main()
{
cout << max(5, 10) << endl;
}
So why isn't there any naming conflict?
您在此处声明了一个非模板 max
,并且 std::max
is a set of overloaded function templates, so they're all overloaded. And the non-template version declared in the global namespace is selected in overload resolution。
F1 is determined to be a better function than F2 if implicit
conversions for all arguments of F1 are not worse than the implicit
conversions for all arguments of F2, and
...
- or, if not that, F1 is a non-template function while F2 is a
template specialization
...
And by using namespace std
I'm importing the function to the global namespace
这是一个常见的误解。没有任何东西是进口的。事实上,将指令 using namespace std;
放在全局命名空间中意味着当在全局命名空间中查找名称时,也会在命名空间 std
.
中查找该名称
std::max
函数仍在命名空间 std
中,它不在全局命名空间中。
您声明的 max
没问题,因为您声明的 ::max
是 std::max
.
的独立实体
当您进行非限定函数调用 max
时,将在全局命名空间以及 namespace std
.
中查找该名称
这两个查找的结果导致一个 重载集 由称为 ::max
和 std::max
.[=24= 的函数的所有签名组成]
然后重载解析从重载集中为提供的参数选择最佳匹配,结果证明 ::max
是更好的匹配,因为非模板函数比函数模板更匹配,所有其他条件都相同。
算法头文件中不是已经有max函数了吗?
通过 using namespace std;
,我将函数导入到全局命名空间(它接受参数,在本例中两者都是整数,因此它不应该是重载)。
那么为什么没有命名冲突呢?
#include <iostream>
#include <algorithm>
using namespace std;
int max(int a, int b)
{
return (a > b) ? a : b;
}
int main()
{
cout << max(5, 10) << endl;
}
So why isn't there any naming conflict?
您在此处声明了一个非模板 max
,并且 std::max
is a set of overloaded function templates, so they're all overloaded. And the non-template version declared in the global namespace is selected in overload resolution。
F1 is determined to be a better function than F2 if implicit conversions for all arguments of F1 are not worse than the implicit conversions for all arguments of F2, and
...
- or, if not that, F1 is a non-template function while F2 is a template specialization
...
And by
using namespace std
I'm importing the function to the global namespace
这是一个常见的误解。没有任何东西是进口的。事实上,将指令 using namespace std;
放在全局命名空间中意味着当在全局命名空间中查找名称时,也会在命名空间 std
.
std::max
函数仍在命名空间 std
中,它不在全局命名空间中。
您声明的 max
没问题,因为您声明的 ::max
是 std::max
.
当您进行非限定函数调用 max
时,将在全局命名空间以及 namespace std
.
这两个查找的结果导致一个 重载集 由称为 ::max
和 std::max
.[=24= 的函数的所有签名组成]
然后重载解析从重载集中为提供的参数选择最佳匹配,结果证明 ::max
是更好的匹配,因为非模板函数比函数模板更匹配,所有其他条件都相同。