Where should you put global constants in a C++ program?

后端 未结 6 1235
日久生厌
日久生厌 2020-12-15 07:35

Where would you put global constants in a C++ application? For example would you put them in a class? In a struct?

6条回答
  •  温柔的废话
    2020-12-15 08:10

    For constants local to a single .cpp file, the best approach is to declare them in an anonymous namespace like so:

    namespace {
       int const seconds_per_minute = 60;
       int const minutes_per_hour   = 60;
    }
    

    For constants that need to be visible to the entire program, the simplest solution is to create a (named) namspace for them, and put that in a header file.

    If there is (or might be) some operations to go with them, instead you should probably create a singleton class for them. For example, it is quite common that my programs have a singleton class named "configuration" that reads startup constants (stuff like IP addresses, and things I don't quite want to hard-code) from a config file or the registry or something like that.

提交回复
热议问题