命名空间c++中的extern变量
extern variable in namespace c++
我有一个关于命名空间c++中的外部变量的问题。这是CBVR类的.h文件
namespace parameters
{
class CBVR
{
private:
std::string database;
public:
CBVR(void);
void initialize(const std::string &fileName);
static void printParameter(const std::string &name,
const std::string &value);
};
extern CBVR cbvr;
}
.cpp文件看起来像:
parameters::CBVR parameters::cbvr;
using namespace xercesc;
parameters::CBVR::CBVR(void)
{
}
void parameters::CBVR::initialize(const std::string &_fileName)
{
}
void parameters::CBVR::printParameter(const std::string &_name, const std::string &_value)
{
if (_value.empty())
{
cbvr << " -> " << _name << " = < EMPTY!!! >" << std::endl;
}
else
{
cbvr << " -> " << _name << " = "" << _value << """ << std::endl;
}
}
在方法printParameter
中,我们使用cbvr
,而不引用任何命名空间。parameters::CBVR parameters::cbvr;
处理它,但我不明白它意味着什么,为什么它允许cbvr
变量在类中这样使用?
编辑:
我这样做了,但上面写着:error: undefined reference to parameters::cbvr
//parameters::CBVR parameters::cbvr;
using namespace parameters;
using namespace xercesc;
CBVR::CBVR(void)
{
}
void CBVR::initialize(const std::string &_fileName)
{
}
void CBVR::printParameter(const std::string &_name, const std::string &_value)
{
if (_value.empty())
{
cbvr << " -> " << _name << " = < EMPTY!!! >" << std::endl;
}
else
{
cbvr << " -> " << _name << " = "" << _value << """ << std::endl;
}
}
那有什么区别呢?
在成员函数的定义中,您处于类的范围内,而类又处于其周围命名空间的范围内。因此,在类或命名空间中声明的任何内容都可以在没有限定的情况下访问。
在命名空间之外,不合格的名称不可用,这就是为什么您需要在变量和函数定义中使用parameters::
资格。
具有
void parameters::CBVR::printParameter(const std::string &_name, const std::string &_value)
{
... }
与相同
namespace parameters
{// notice, the signature of the method has no "parameters" before CBVR
void CBVR::printParameter(const std::string &_name, const std::string &_value)
{
... }
}
类在命名空间的作用域中,因此您正在实现的类的主体也在作用域中。
相关文章:
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 可视化编译与 C++ 中的 Extern 变量
- 是否可以在不使用 decltype 的情况下推断先前定义的 extern 变量的类型
- 如何与 Cheerp/js 中的 extern 变量接口?
- 从 exe 和 dll 访问静态库中的 extern 变量
- 既然我们有内联变量,extern const 还有用吗?
- 在命名空间 c++ 中正确声明 extern 变量
- 静态变量,后跟同一文件中的 extern
- 为什么我不能在标头中只定义一个非常量 gloabal 变量?如果我使用命名空间,为什么我必须声明它"extern"?
- 在不同的文件中使用相同的变量(使用 extern)
- 模板类静态成员变量在使用'extern template class'语法时的特殊化
- 为什么我应该使用extern关键字来声明命名空间范围中的变量
- 在未包含在任何其他文件中的文件中使用 extern 变量是否有任何可能的用途
- 从另一个文件访问 c++ 中的 extern "C"变量
- 默认情况下全局变量是 extern 还是等效于在全局中使用 extern 声明变量
- 是否必须从其他线程访问 extern 变量
- 命名空间c++中的extern变量
- 如何使用 extern 在 C++ 中的源文件之间共享地球变量
- C++ extern 关键字和全局变量
- 在 main() 与全局中定义 extern 变量