为什么命名空间内的自由功能模棱两可
why free function inside namespace is ambiguous?
- myfunc.hh
#ifndef MY_FUNC_HH
#define MY_FUNC_HH
namespace abc
{
int xyz (int a, int b);
}
#endif
- myfunc.cc
#include "myfunc.hh"
using namespace abc;
int xyz (int a, int b)
{
if (!b)
return 0;
return xyz (b, b/a);
}
$ g++ -c -g myfunc.cc myfunc.hh
myfunc.cc: In function ‘int xyz(int, int)’:
myfunc.cc:9: error: call of overloaded ‘xyz(int&, int)’ is ambiguous
myfunc.cc:5: note: candidates are: int xyz(int, int)
myfunc.hh:6: note: int abc::xyz(int, int)
为什么只有一个名为xyz定义的功能时,xyz
在此处定义?
using namespace abc
难道不是告诉编译器在名称空间ABC中寻找名称XYZ吗?例如,当您使用std ::复制功能
#include <algorithm>
using namespace std;
void afunction()
{
copy(blah, blah, blah);
}
一切都很好,为什么这里应该在这里有什么不同?还是因为递归电话?如果是这样,为什么?
我想在myfunc.cc中您想写
#include "myfunc.hh"
namespace abc {
int xyz (int a, int b)
{
if (!b)
return 0;
return xyz (b, b/a);
}
}
这样,您定义您在.h
文件中声明的abc::xyz
函数。您写的方式是在名称空间abc
之外定义xyz
函数,同时还导入在命名空间中声明的函数。因此,歧义。
同意@chao和@jonathanwakely的建议,我赞成这个更好的语法:
int abc::xyz (int a, int b)
{
if (!b)
return 0;
return xyz (b, b/a);
}
的确,它确保在标题文件中正确声明了abc::xyz
。
这两个代码之间存在差异:
- myfunc.cc
#include "myfunc.hh"
using namespace abc;
int xyz (int a, int b)
{
if (!b)
return 0;
return xyz (b, b/a);
}
- myfunc.cc
#include "myfunc.hh"
namespace abc {
int xyz (int a, int b)
{
if (!b)
return 0;
return xyz (b, b/a);
}
}
首先使用abc
名称空间,但是xyz
在"顶部"名称空间中定义;定义了2个函数。第二个给出了abc::xyz
函数的实现。
在您的情况下,您想做第二次。
在您的myfunc.cc
文件中,您超载XYZ。这意味着您正在定义一个全新的功能。在全球名称空间中有一个是 local ,名称空间abc
中有一个。
您的示例中的语句using namespace abc;
实际上引入了歧义,而不是解决它。您的呼叫是模棱两可的,因为编译器不知道要调用哪个功能。
您的问题似乎在问为什么当您明确去告诉编译器时可见xyz(int, int)
的两个版本可见,然后使xyz(int, int)
可见,然后定义另一个?
,您确切希望编译器在这里做什么?它不会为您猜测,所以会给您带来错误。
如果您需要调用一个或另一个,请使用范围操作员和一个显式名称空间。您可以致电::xyz(1, 2)
或abc::xyz(1, 2)
。
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 文件系统:复制功能的速度秘诀是什么
- 模棱两可的功能超载[例如最大限度()]
- GCC称将功能与多个继承过载时,称其为模棱两可,但Clang和MSVC没有
- C 从同一基本模板类覆盖功能,具有多个继承模棱两可的函数调用
- 为模棱两可的超载功能调用创建默认值
- 为什么命名空间内的自由功能模棱两可
- 重载功能。为什么这里模棱两可?