[英]using namespace does not work for definitions?
I am having trouble understanding c++ namespaces. 我无法理解c ++名称空间。 Consider the following example:
请考虑以下示例:
//distr.h
namespace bogus{
extern const int x;
extern const int y;
double made_up_distr(unsigned param);
}
Now if I define my variables like the cpp below everything compiles fine 现在如果我将变量定义为下面的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;
}
But if I try to simply bring in the bogus
namespace and use instead 但是,如果我试图简单地引入
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;
}
My compiler tells me that the reference to x
and y
is ambiguous. 我的编译器告诉我,对
x
和y
的引用是不明确的。 Why is that? 这是为什么?
There's a simple reason why this can't plausibly work the way you expected: 有一个简单的原因,为什么这不能按预期的方式运作:
namespace bogus {
const int x;
}
namespace heinous {
const int x;
}
using namespace bogus;
using namespace heinous;
const int x = 10;
now, should x
above refer to bogus::x
, heinous::x
or a new global ::x
? 现在,上面的
x
应该引用bogus::x
, heinous::x
还是新的global ::x
? It would be the third without the using
statements, which means here that adding a using statement would change the meaning of existing code in a particularly subtle way. 它将是没有
using
语句的第三个,这意味着添加using语句将以一种特别微妙的方式改变现有代码的含义。
The using statement is used to introduce the contents of a scope (usually but not necessarily a namespace) for lookup . using语句用于引入范围的内容(通常但不一定是命名空间)以供查找 。 The statement
该声明
const int x = 10;
wouldn't normally require a lookup in the first place, except to detect an ODR violation. 除了检测ODR违规外,通常不需要首先查找。
Name lookup for the identifier in declarations/definitions doesn't work the same way as name lookup in usage. 声明/定义中的标识符的名称查找与使用中的名称查找的工作方式不同。 In particular, it doesn't care about using statements.
特别是,它不关心使用语句。 There is a very simple reason for this: if it were different, it would lead to all sorts of nasty surprises.
这有一个非常简单的原因:如果它不同,它将导致各种令人讨厌的惊喜。 Consider this:
考虑一下:
// sneakattack.h
namespace sneakattack { void foo(); }
using namespace sneakattack;
// somefile.cpp
#include "sneakattack.h"
void foo() { std::cout << "Hello\n"; }
// otherfile.cpp
void foo();
int main() { foo(); }
This program currently works: the declaration sneakattack::foo
is ignored, and the definition ::foo
is correctly linked to the use in otherfile. 这个程序目前有效:声明
sneakattack::foo
被忽略,定义::foo
正确链接到otherfile中的用法。 But if name lookup worked differently, somefile would suddenly define sneakattack::foo
, not ::foo
, and the program would fail to link. 但是如果名称查找工作方式不同,
sneakattack::foo
会突然定义sneakattack::foo
,而不是::foo
,程序将无法链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.