在https://repl.it/@JomaCorpFX/NameCollision#main.cpp 上检查/测试此代码
#include <iostream>
namespace std{
static int Add(int a, int b)
{
return a + b;
}
}
namespace math{
static int Add(int a, int b)
{
return a + b;
}
}
static int Add(int a, int b)
{
return a + b;
}
using namespace std;
using namespace math;
int main() {
std::cout << std::Add(1,2) << std::endl; //OK
std::cout << math::Add(1,2) << std::endl; //OK
std::cout << ::Add(1,2) << std::endl; //OK
std::cout << Add(1,2) << std::endl;//ERROR. Ambiguous call to "std::Add" or "math::Add" or local function "Add" // Comment this line for fix the error or complete the correct namespace or delete using namespace statements.
}
编译时输出
main.cpp:29:16: error: call to 'Add' is ambiguous
std::cout << Add(1,2) << std::endl;//ERROR. Ambiguous call to "std::Ad...
^~~
main.cpp:4:14: note: candidate function
static int Add(int a, int b)
^
main.cpp:11:14: note: candidate function
static int Add(int a, int b)
^
main.cpp:17:12: note: candidate function
static int Add(int a, int b)
^
1 error generated.
compiler exit status 1
如果您键入“using namespace std”语句,您可能会导致函数名称/签名冲突,另一个标头可以包含相同的函数签名而没有命名空间。
如果您包含一个新标头,该标头可以包含 1 个或 n 个函数,这些函数会使用您的代码对签名进行数学运算,那么您的原始代码可能会中断。编译器显示代码错误,很头疼。
最佳做法是使用完整名称,以避免这种情况。花更多的时间,获得更多的可读性并减少错误。
std::Add
math::Add
::Add
std::cout
std::string
为了约定,只有 C++ 标准库可以有命名空间 std。