0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C++】staticメンバにinlineを使うと、宣言と初期化を同時にできる

Posted at

クラスのメンバを作る場面。
普通の書き方はこれ。

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
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?