全局命名空间(C++)中的两个函数没有命名冲突

No naming conflict from two functions in global namespace (C++)?

本文关键字:函数 两个 冲突 C++ 命名空间 全局      更新时间:2024-05-24
我创建了两个文件,Linkage.cppExternal.cpp

Linkage.cpp:

#include <iostream>
void Log(int x = 5)
{
std::cout << x << "n";
}
int main()
{
Log();
return 0;
}

External.cpp:

#include <iostream>
void Log(const char* message)
{
std::cout << message << "n";
}

为什么我没有收到链接器错误?这两个函数都是在全局命名空间中定义的,因此应该像使用变量一样存在命名冲突。

为什么我没有得到链接器错误?

当你写时

void Log(int x = 5)//this means that the function named Log can be called without passing 
//any argument because you have provided a default argument which will be 
//used in case you don't provide/pass any argument
{
//..other code here
{

上面的意思是,可以在不传递任何参数的情况下调用名为Log的函数,因为您提供了一个默认参数,该参数将在您不提供/传递任何参数时使用。

下一步当您编写时

void Log(const char* message)//this means that this versoin of the function named Log will be called only if you pass an argument of type `char*` . 
{
std::cout << message << "n";
}

上面的意思是,只有当传递类型为char*的参数时,才会调用名为Log的函数的此版本。

现在当你写下:

Log();

将使用具有默认参数的第一个版本,因为您没有提供任何参数,因此可以使用第一个版本(因为它是可行(,并且因为必须采用参数的第二个版本是不可行

好吧,在@Retire Ninja向我指出这一点后,我四处实验。

首先,注释掉External.cpp中的所有代码。现在,在Linkage.cpp中声明另一个Log函数,以便在该文件中有两个名称(Log(相同但参数不同的函数。您将意识到,根据您提供的参数,这些Log函数的行为将类似于不同的函数。

因此,与变量不同,在变量中,相同的名称意味着命名空间中的相同变量,函数也需要具有匹配的签名