クラスのメンバを作る場面。
普通の書き方はこれ。
class MyClass
{
int value = 0;
};
しかし、staticメンバの場合は、メンバがconstでないとコンパイルエラーになる。
クラス外で定義を書け、とのこと。
class MyClass
{
// non-const static data member must be initialized out of line
static int value = 0; // コンパイルエラー
static const int value = 0; // これはOK
};
そこで、 inline
修飾子を使うと、宣言と初期化を同時に行えるようになる。
class MyClass
{
inline static int value = 0;
};
補足
constexpr
の場合、コンパイル時定数なので、 static
を付けないとコンパイルエラーになる。
inline
は必要ない。というより、 constexpr
の時点で inline
が付いているものとみなされる。
class MyClass
{
// non-static data member cannot be constexpr; did you intend to make it static?
constexpr int value = 0; // コンパイルエラー
static constexpr int value = 0; // これはOK
};