How to declare a static const char* in your header file?

后端 未结 9 1074
盖世英雄少女心
盖世英雄少女心 2021-01-31 13:26

I\'d like to define a constant char* in my header file for my .cpp file to use. So I\'ve tried this:

private:
    static const char *SOMETHING = \"sommething\";         


        
9条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 14:17

    With C++11 you can use the constexpr keyword and write in your header:

    private:
        static constexpr const char* SOMETHING = "something";
    


    Notes:

    • constexpr makes SOMETHING a constant pointer so you cannot write

      SOMETHING = "something different";
      

      later on.

    • Depending on your compiler, you might also need to write an explicit definition in the .cpp file:

      constexpr const char* MyClass::SOMETHING;
      

提交回复
热议问题