Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
158 views
Welcome To Ask or Share your Answers For Others

1 Answer

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};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...