简体   繁体   中英

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

In my project, there are two classes named 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:

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

Configuration.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

How to solve this problem, and why the complier treat "std::string ::Configuration" as "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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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