Define constant variables in C++ header

前端 未结 6 1382
既然无缘
既然无缘 2020-11-30 18:30

A program I am working on has many constants that apply throughout all classes. I want to make one header file \"Constants.h\", and be able to declare all the relevant const

6条回答
  •  广开言路
    2020-11-30 19:16

    I like the namespace better for this kind of purpose.

    Option 1 :

    #ifndef MYLIB_CONSTANTS_H
    #define MYLIB_CONSTANTS_H
    
    //  File Name : LibConstants.hpp    Purpose : Global Constants for Lib Utils
    namespace LibConstants
    {
      const int CurlTimeOut = 0xFF;     // Just some example
      ...
    }
    #endif
    
    // source.cpp
    #include 
    int value = LibConstants::CurlTimeOut;
    

    Option 2 :

    #ifndef MYLIB_CONSTANTS_H
    #define MYLIB_CONSTANTS_H
    //  File Name : LibConstants.hpp    Purpose : Global Constants for Lib Utils
    namespace CurlConstants
    {
      const int CurlTimeOut = 0xFF;     // Just some example
      ...
    }
    
    namespace MySQLConstants
    {
      const int DBPoolSize = 0xFF;      // Just some example
      ...
    }
    #endif
    
    
    
    // source.cpp
    #include 
    int value = CurlConstants::CurlTimeOut;
    int val2  = MySQLConstants::DBPoolSize;
    

    And I would never use a Class to hold this type of HardCoded Const variables.

提交回复
热议问题