Can I initialize a static const member at run-time in C++?

前端 未结 11 1089
小蘑菇
小蘑菇 2020-12-09 16:22

Is it possible to initialize a static const member of my class during run-time? This variable is a constant throughout my program but I want to send it as a command-line arg

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 16:56

    Typically you will have more than one configuration value. So put them in a struct, and the normal global access to it is const.

    const config* Config;
    ...
    main (int argc, char* argv [])
    {
    Config= new config (argc, argv);
    ...
    }
    

    You can get fancier and have a global function to return config, so normal code can't even change the pointer, but it is harder to do that by accident.

    A header file exposes get_config () for all to use, but the way to set it is only known to the code that's meant to do so.

提交回复
热议问题