LoginSignup
8
6

More than 5 years have passed since last update.

enumのコンストラクト、++演算、変換関数

Last updated at Posted at 2014-07-22

列挙体にもコンストラクタがあるのを知った。

enum Nums{ one = 1, two, three };
Nums( e + 1 ); // eはNums型の変数

これが便利なのは列挙型の戻り型、または参照仮引数をもつ関数で初期化できる。

enum Nums{ one = 1, two, three };
Nums operator++( Nums& n )
{
    n = ( n == three ) ? three : Nums( n + 1 );
    return n;
}

注:このサンプルは「ストラウストラップのプログラミング入門」にあるサンプルと同じ内容のもの。

 決定的に重要なのは列挙型の戻り型、または参照仮引数をもつ関数で初期化できるということ。
つまり、代入演算子の左辺にある列挙型オブジェクトを右辺の列挙型を返す関数で初期化できる。
あるいは ()演算子で初期化できる。

簡単なサンプルを示す。

struct Set
{
    enum Nums{ one = 1, two, three };

    // 変換関数(intに変換)
    int operator()( Set::Nums& n )
    {
        int c = n;
        return c;
    }
};

// 列挙子のインクリメント
Set::Nums operator++( Set::Nums& n )
{
    n = ( n == Set::three ) ? Set::three : Set::Nums( n + 1 );
    return n;
}

int main()
{

    Set::Nums n(Set::one);
    Set t;

    ++n;

    //intに変換して出力
    std::cout << t(n) << std::endl;
    return 0;
}
8
6
1

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
8
6