我在理解 c++ 命名空间时遇到问题。考虑以下示例:

//distr.h

namespace bogus{
    extern const int x;
    extern const int y;
    double made_up_distr(unsigned param);
}

现在,如果我像下面的 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;
}

但是,如果我尝试简单地引入 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;
}

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

最佳答案

有一个简单的原因为什么这不能像您预期的那样工作:

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

using namespace bogus;
using namespace heinous;

const int x = 10;

现在,上面的 x 是指 bogus::xheinous::x 还是新的全局 ::x
这将是没有 using 语句的第三个,这意味着添加 using 语句会以一种特别微妙的方式改变现有代码的含义。

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

通常不需要首先进行查找,除非检测 ODR 违规。

关于c++ - 使用命名空间不适用于定义?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17790602/

10-11 23:17
查看更多