相同的函数名称在不同的命名空间中
Same function name in different namespaces
假设我有不同的名称空间类似于apple命名空间和orange命名空间,但这两个命名空间都包含一个名为myfunction()的函数。
当我在main()中调用myfunction()时会发生什么?
这正是引入命名空间的目的。
在main()
中,或者通常在全局命名空间中,您将能够选择必须调用哪个myfunctions
:
int main()
{
apple::myfunction(); // call the version into the apple namespace
orange::myfunction(); // call the orange one
myfunction(); // error: there is no using declaration / directive
}
在使用指令 (using namespace apple
)或使用声明 (using apple::myfunction
)的情况下,主程序的最后一行将调用名称空间apple
中的版本。如果两个版本的myfunction
都在作用域中,最后一行将再次产生错误,因为在这种情况下,您必须指定必须调用哪个函数。
考虑以下示例:
namespace Gandalf{
namespace Frodo{
bool static hasMyPrecious(){ // _ZN7Gandalf5FrodoL13hasMyPreciousEv
return true;
}
};
bool static hasMyPrecious(){ // _ZN7GandalfL13hasMyPreciousEv
return true;
}
};
namespace Sauron{
bool static hasMyPrecious(){ // _ZN5SauronL13hasMyPreciousEv
return true;
}
};
bool hasMyPrecious(){ // _Z13hasMyPreciousv
return true;
}
int main()
{
if( Gandalf::Frodo::hasMyPrecious() || // _ZN7Gandalf5FrodoL13hasMyPreciousEv
Gandalf::hasMyPrecious() || // _ZN7GandalfL13hasMyPreciousEv
Sauron::hasMyPrecious() || // _ZN5SauronL13hasMyPreciousEv
hasMyPrecious()) // _Z13hasMyPreciousv
return 0;
return 1;
}
对于声明函数的命名空间,编译器生成每个函数的唯一标识,称为Mangled Name,这只不过是定义函数的命名空间作用域、函数名称、返回类型和实际参数的编码。看到评论。当您创建对此函数的调用时,每个函数调用都会查找相同的损坏签名,如果没有找到,编译器会报告错误。
尝试使用clang -emit-llvm -S -c main.cpp -o main。
相关文章:
- 在命名空间中定义函数还是限定函数
- CUDA内核和数学函数的显式命名空间
- 在命名空间中使用全局命名空间中的函数
- 是否可以将函数导入命名空间,但不能导出它?
- 使用另一个命名空间中的函数C++
- Visual Studio 无法解决类和命名空间中重载的明确函数
- 命名空间更改函数定义
- C++命名空间中调用 void 函数的错误
- C++ 17 个友元函数声明和内联命名空间
- MFC 函数来自 :: 命名空间?
- 使用类指针重载C++命名空间函数模板专用化替代方法?
- 在头文件中添加命名空间函数
- 命名空间函数的多重定义
- 在多个 cpp 文件中重用未命名的命名空间函数
- 如何正确声明命名空间函数
- 使用 libclang 解析命名空间函数
- C++命名空间函数
- 内联命名空间函数时出错
- 递归std::functional与递归匿名命名空间函数.使用哪一个
- 如何在命名空间函数中使用pragma weak