Define constant variables in C++ header

前端 未结 6 1369
既然无缘
既然无缘 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:19

    Rather than making a bunch of global variables, you might consider creating a class that has a bunch of public static constants. It's still global, but this way it's wrapped in a class so you know where the constant is coming from and that it's supposed to be a constant.

    Constants.h

    #ifndef CONSTANTS_H
    #define CONSTANTS_H
    
    class GlobalConstants {
      public:
        static const int myConstant;
        static const int myOtherConstant;
    };
    
    #endif
    

    Constants.cpp

    #include "Constants.h"
    
    const int GlobalConstants::myConstant = 1;
    const int GlobalConstants::myOtherConstant = 3;
    

    Then you can use this like so:

    #include "Constants.h"
    
    void foo() {
      int foo = GlobalConstants::myConstant;
    }
    

提交回复
热议问题