How to cast int to enum in C++?

前端 未结 5 2204
旧巷少年郎
旧巷少年郎 2020-12-12 17:49

How do I cast an int to an enum in C++?

For example:

enum Test
{
    A, B
};

int a = 1;

How do I convert a to type

5条回答
  •  长情又很酷
    2020-12-12 18:14

    Test castEnum = static_cast(a-1); will cast a to A. If you don't want to substruct 1, you can redefine the enum:

    enum Test
    {
        A:1, B
    };
    

    In this case Test castEnum = static_cast(a); could be used to cast a to A.

提交回复
热议问题