[英]C++ Namespace error : not a member of namespace
我已经在头文件中将命名空间中的变量声明为 extern,比如说啊,我将这个文件包含在一个 .cpp 文件中,比如 a.cpp 并在同一个命名空间中定义该变量。 这工作正常。
现在,我将这个头文件包含在另一个 .cpp 文件中,比如 b.cpp 并在不同的命名空间中使用这个变量。 这向我抛出错误,指出变量“a”未在此范围内声明。 我在 b.cpp 文件中使用“使用命名空间”包含命名空间。 我仍然得到同样的错误。 在 b.cpp 中使用表达式 namespace::variable 会出现错误,指出变量 'a' 不是该命名空间的成员。
以下是用于理解我的问题的代码片段。
// a.h
namespace example1
{
extern int a;
}
// a.cpp
#include"a.h"
namespace example1
{
a = 10;
}
// b.cpp
#include"a.h"
namespace example2
{
a = 5; // error : 'a' not declared in this scope.
}
// b.cpp
#include"a.h"
using namespace example1;
namespace example2
{
a = 5; // error : 'a' not declared in this scope.
}
// b.cpp
#include"a.h"
namespace example2
{
example1::a = 5; // error : 'a' not a member of example1.
}
在 ah 中,您将变量声明为 extern,因此定义必须出现在 cpp 文件中(翻译单元是正确的):
// a.h
namespace example1
{
extern int a;
}
所以这里是你定义变量的文件:
// a.cpp
#include"a.h"
namespace example1
{
int a = 10;
}
现在您使用 a.cpp 中定义的变量a
// b.cpp
#include"a.h"
namespace example2
{
void f(){
a = 5; // error : 'a' not declared in this scope.
}
}
事实上,a 在命名空间 example1 中,a 不是限定名称并且编译器失败。 (编译器在命名空间 ::example2 及其父级中查找全局命名空间)
第二个例子:
// b.cpp
#include"a.h"
using namespace example1;
namespace example2
{
void f(){
a = 5;
}
}
这应该可以编译,因为现在a
在全局命名空间范围内可见。 但是,如果您现在仍然看到错误,则应该是在链接阶段。 构建可执行文件之前,链接器将要寻找的定义a
,所以你也必须给他编译a.cpp的结果。 例如,如果您使用 GCC,请使用此命令行c++ b.cpp a.cpp
。
这也适用于这个例子:
// b.cpp
#include"a.h"
namespace example2
{
void f(){
example1::a = 5;
}
}
在这里您执行限定名称查找,因此它应该编译。 如果发生错误,这应该是在前一个示例中描述的链接时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.