为什么命名空间内的自由功能模棱两可

why free function inside namespace is ambiguous?

本文关键字:功能 模棱两可 自由 命名空间 为什么      更新时间:2023-10-16

- 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)