C++ < 11 : Initialize static const class member

烂漫一生 提交于 2019-12-25 17:56:09

问题


So I have a class which has mostly static stuff because it needs to be a library accessible at all times with no instantiation. Anyway, this class has a public static member, a structure called cfg, which contains all of its configuration parameters (mostly boundaries and tolerances for the algorithms implemented by its static methods). And on top it has a const static member, which is a structure of the same type as cfg, but has all the default / usual values for the parameters. Users of my module may load it, modify it in part, and apply it as cfg, or use it as reference, or what do I know.

Now I can't seem to initialize this guy, at all. With no instantiation (and it being static) initialization won't happen in a constructor (there is none anyway). In-class init returns an error, init in the cpp returns a declaration conflict. What's the way forward here ?

Here an example with exact same behavior as I get :

module.h :

#ifndef MODULE_H
#define MODULE_H

typedef struct {
    float param1;
    float param2;
} module_cfg;

class module
{
    public:
        module();
        static module_cfg cfg;
        const static module_cfg default_cfg;

};

#endif // MODULE_H

module.cpp :

#include "module.h"
using namespace std;

module_cfg module::default_cfg = {15, 19};

int main(int argc, char* argv[])
{
    //clog << "Hello World!" << endl << endl;

    return 0;
}

module::module()
{
}

Errors with above :

module.cpp:11:20: error: conflicting declaration 'module_cfg module::default_cfg' module_cfg module::default_cfg = {15, 19}; ^ In file included from module.cpp:8:0: module.h:14:29: error: 'module::default_cfg' has a previous declaration as 'const module_cfg module::default_cfg' const static module_cfg default_cfg; ^ Makefile.Debug:119: recipe for target 'debug/module.o' failed module.cpp:11:20: error: declaration of 'const module_cfg module::default_cfg' outside of class is not definition [-fpermissive] module_cfg module::default_cfg = {15, 19};

Thanks in advance,

Charles


回答1:


The errors above are due to the fact that you are inadvertently redeclaring default_cfg to be mutable in the cpp file.

adding const to the definition fixes it:

const module_cfg module::default_cfg = {15, 19};


来源:https://stackoverflow.com/questions/36687185/c-11-initialize-static-const-class-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!