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?

More than 1 year has passed since last update.

メンバ変数に配列を持つ時のサイズの定義

Last updated at Posted at 2023-02-05

TL;DR

メンバ変数に配列を持つ時、サイズの指定はstatic constexprを使えばいい。

class Manager
{
public:
    Manager()
        : m_item{0}
        {};
private:
    static constexpr int ITEM_NUM = 10;
    int m_item[ITEM_NUM];
};

ダメな方法

メンバ変数を使う

  • コンパイルエラーになる
class Manager
{
public:
    Manager()
        : m_item{0}
        {};
private:
    int ITEM_NUM = 10;
    int m_item[ITEM_NUM];
};

constのメンバ変数を使う

  • これもコンパイルエラー
class Manager
{
public:
    Manager()
        : m_item{0}
        {};
private:
    const int ITEM_NUM = 10;
    int m_item[ITEM_NUM];
};

static constのメンバ変数を使う

  • これはコンパイラによってはリンクエラーになるので、あまり良いとは言えない
    • VisualStudioなどではエラーにならない
class Manager
{
public:
    Manager()
        : m_item{0}
        {};
private:
    static const int ITEM_NUM = 10;
    int m_item[ITEM_NUM];
};

static constexprのメンバ変数を使う

  • ということで、冒頭のとおりstatic constexprを使えばいい
class Manager
{
public:
    Manager()
        : m_item{0}
        {};
private:
    static constexpr int ITEM_NUM = 10;
    int m_item[ITEM_NUM];
};
0
0
4

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?