【问题标题】:extern variable in namespace c++命名空间c ++中的外部变量
【发布时间】:2015-02-09 15:48:57
【问题描述】:

我对命名空间 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;
    }
}

那有什么区别呢?

【问题讨论】:

    标签: c++ namespaces global-variables extern


    【解决方案1】:

    在成员函数的定义中,您处于类的范围内,而类又处于其周围命名空间的范围内。因此,在类或命名空间中声明的任何内容都可以在没有限定条件的情况下访问。

    在命名空间之外,非限定名称不可用,这就是为什么您需要在变量和函数定义中使用parameters:: 限定符。

    【讨论】:

    • @Maystro:你注释掉了cvbr 的定义,所以链接器抱怨它没有定义。你为什么要这么做?
    • 我只是想了解其中的区别以及它究竟做了什么“parameters::CBVR parameters::cbvr”?你说的定义?它已经在命名空间中定义了,不是吗?
    • @Maystro:不,它已在标题中声明(未定义) - 这就是 extern 的含义。声明声明它存在,但没有为它分配任何存储空间。它还必须在一个源文件中定义为可用。这就是原始源文件的第一行所做的,您在更新中将其注释掉。
    【解决方案2】:

    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)
        {
            ...    }
    }
    

    类在命名空间的范围内,所以你正在实现的类的主体也在范围内。

    【讨论】:

      猜你喜欢
      • 2011-05-11
      • 2017-10-05
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      相关资源
      最近更新 更多