c++ 静态成员变量 static

创建日期: 2024-05-28 16:29 | 作者: 风波 | 浏览次数: 13 | 分类: C++

来源:https://stackoverflow.com/questions/1563897/how-can-you-define-a-static-data-member-of-type-const-stdstring

C++17

Since C++17, you can use an inline variable:

// In a header file (if it is in a header file in your case)
class A {   
private:      
  inline static const string RECTANGLE = "rectangle";
};

或者

class A {
 private:
  static constexpr std::string_view STRING = "some useful string constant";
};

In C++14 and C++11, you can use constexpr const char* instead of constexpr std::string_view

C++11/C++14

Prior to C++17, you have to define your static member outside the class definition and provide the initializer there.

// In a header file (if it is in a header file in your case)
class A {   
private:      
  static const string RECTANGLE;
};
// In one of the implementation files
const string A::RECTANGLE = "rectangle";
13 浏览
11 爬虫
0 评论