C++ < 11 : Initialize static const class member

2019-09-19 13: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条回答
混吃等死
2楼-- · 2019-09-19 13:43

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};
查看更多
登录 后发表回答