使用命名空间不适用于定义?

dud*_*udu 4 c++ namespaces

我无法理解c ++名称空间.请考虑以下示例:

//distr.h

namespace bogus{
    extern const int x;
    extern const int y;
    double made_up_distr(unsigned param);
}
Run Code Online (Sandbox Code Playgroud)

现在如果我将变量定义为下面的cpp,那么编译就好了

//distr.cpp

#include "distr.h"
#include <cmath>

const int bogus::x = 10;   
const int bogus::y = 100;

double bogus::made_up_distr(unsigned param){
    auto pdf = (exp(param) / bogus::x) + bogus::y;
    return pdf;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试简单地引入bogus命名空间并使用它

//broken distr.cpp

#include "distr.h"
#include <cmath>

using namespace bogus;

const int x = 10;
const int y = 100;

double made_up_distr(unsigned param){
    auto pdf = (exp(param) / x) + y;
    return pdf;
}
Run Code Online (Sandbox Code Playgroud)

我的编译器告诉我,引用xy不明确.这是为什么?

Use*_*ess 6

有一个简单的原因,为什么这不能按预期的方式运作:

namespace bogus {
    const int x;
}
namespace heinous {
    const int x;
}

using namespace bogus;
using namespace heinous;

const int x = 10;
Run Code Online (Sandbox Code Playgroud)

现在,应该x在上面提到bogus::x,heinous::x还是一个新的全球::x?它将是没有using语句的第三个,这意味着添加using语句将以特别微妙的方式改变现有代码的含义.

using语句用于引入范围的内容(通常但不一定是命名空间)以供查找.该声明

const int x = 10;
Run Code Online (Sandbox Code Playgroud)

除了检测ODR违规外,通常不需要首先查找.