命名空间c++中的extern变量

extern variable in namespace c++

本文关键字:变量 extern 中的 c++ 命名空间      更新时间:2023-10-16

我有一个关于命名空间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)
    {
        ...    }
}

类在命名空间的作用域中,因此您正在实现的类的主体也在作用域中。