★定数を使った配列宣言★


C++の定数関係でありがちな事を書きます。

配列の宣言時には要素数を指定する必要がありますので、そこで定数を使います。

<sample program cpp057-01>

#include <iostream>

class Field {
public:

    Field();

    const int CONST_SIZE;                     //1

    static const int STATIC_CONST_SIZE;       //2

    const int CONST_SIZE2 = 10;               //3

    static const int STATIC_CONST_SIZE2 = 10; //4

private:

    int m_constArray[CONST_SIZE];                //1

    int m_staticConstArray[STATIC_CONST_SIZE];   //2

    int m_constArray2[CONST_SIZE2];              //3

    int m_staticConstArray2[STATIC_CONST_SIZE2]; //4
};

int main()
{   
    return 0;
}

const int Field::STATIC_CONST_SIZE = 10;

Field::Field() : CONST_SIZE(10)
{

}

1は、定数をコンストラクタ関数の初期化リストで初期化して配列の要素数にしましたがエラーです。

2は、staticを付けて、クラスの外で初期値を入れてみましたがエラーです。

3は、定数の宣言時に初期値を入れてみましたがエラーです。

4は、static定数の宣言時に初期値を入れましたが、これだけがエラーになりません。

また、列挙体を使った「enumハック」という方法もあります。

<sample program cpp055-06>

#include <iostream>

class Field {
public:

private:

    enum { ENUM_SIZE = 10 };
    int m_enumArray[ENUM_SIZE];
};

int main()
{   
    return 0;
}

配列をメンバとして用意する際には、気を付けてください。


次へ

戻る

目次へ