简体   繁体   English

如何在C++中初始化属于全局范围的静态成员

[英]How to initialize static members which belong to global scope in c++

In my project, there are two classes named Configuration.在我的项目中,有两个名为 Configuration 的类。 One is in the namespace common.一种是在公共名称空间中。 The other has no namespace, so it's in global scope.The class in global scope is like this: Configuration.h:另一个没有命名空间,所以在全局范围内。 全局范围内的类是这样的:Configuration.h:

class Configuration
{
    public:
        static int a;
        static string b;
        void func();
}

Configuration.cpp:配置.cpp:

#include "Configuration.h"
int ::Configuration a; //ok
std::string ::Configuration b;//error,the complier treat it like this "std::string::Configuration"

The message from complier is like this: configuration.cpp:17: error: 'std::string::Configuration' has not been declared来自编译器的消息是这样的: configuration.cpp:17: error: 'std::string::Configuration' has not been denied

How to solve this problem, and why the complier treat "std::string ::Configuration" as "std::string::Configuration"?如何解决这个问题,为什么编译器将“std::string::Configuration”视为“std::string::Configuration”?

You don't need to use the global scope explicitly here, you can just omit the :: .您不需要在这里显式使用全局范围,您可以省略::

int Configuration::a;
std::string Configuration::b;

If you really want to, you need to create one extra level of indirection somehow:如果你真的想要,你需要以某种方式创建一个额外的间接级别:

typedef ::Configuration conf;
std::string conf::b;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM