C/CPP: Enum Class vs. Enum Type

51 篇文章 2 订阅

from: Enum Classes in C++ and Their Advantage over Enum DataType - GeeksforGeeksicon-default.png?t=LA92https://www.geeksforgeeks.org/enum-classes-in-c-and-their-advantage-over-enum-datatype/

Enums or Enumerated type (enumeration) is a user-defined data type that can be assigned some limited values. These values are defined by the programmer at the time of declaring the enumerated type.

Need for Enum Class over Enum Type: 
Below are some of the reasons as to what are the limitations of Enum Type and why we need Enum Class to cover them.

Two enumerations cannot share the same names (of values): 

#include <bits/stdc++.h>

using namespace std;



int main()

{

    // Defining enum1 Gender

    enum Gender { Male,

                  Female };



    // Defining enum2 Gender2 with same values

    // This will throw error

    enum Gender2 { Male,

                   Female };



    // Creating Gender type variable

    Gender gender = Male;

    Gender2 gender2 = Female;



    cout << gender << endl

         << gender2;



    return 0;

}

Compilation Error: 

prog.cpp:13:20: error: redeclaration of 'Male'
     enum Gender2 { Male,
                    ^
prog.cpp:8:19: note: previous declaration 'main()::Gender Male'
     enum Gender { Male,
                   ^
prog.cpp:14:20: error: redeclaration of 'Female'
                    Female };
                    ^
prog.cpp:9:19: note: previous declaration 'main()::Gender Female'
                   Female };
                   ^
prog.cpp:18:23: error: cannot convert 'main()::Gender' 
to 'main()::Gender2' in initialization
     Gender2 gender2 = Female;
                       ^

No variable can have a name which is already in some enumeration:

#include <bits/stdc++.h>

using namespace std;



int main()

{

    // Defining enum1 Gender

    enum Gender { Male,

                  Female };


    // Creating Gender type variable

    Gender gender = Male;


    // creating a variable Male

    // this will throw error

    int Male = 10;


    cout << gender << endl;


    return 0;

}

Compilation Error: 

prog.cpp: In function 'int main()':
prog.cpp:16:9: error: 'int Male' redeclared as different kind of symbol
     int Male = 10;
         ^
prog.cpp:8:19: note: previous declaration 'main()::Gender Male'
     enum Gender { Male,
                   ^

Enums are not type-safe:
 

#include <bits/stdc++.h>

using namespace std;



int main()

{

    // Defining enum1 Gender

    enum Gender { Male,

                  Female };



    // Defining enum2 Color

    enum Color { Red,

                 Green };



    // Creating Gender type variable

    Gender gender = Male;

    Color color = Red;



    // Upon comparing gender and color

    // it will return true as both have value 0

    // which should not be the case actually

    if (gender == color)

        cout << "Equal";



    return 0;

}

Warning: 

prog.cpp: In function 'int main()':
prog.cpp:23:19: warning: comparison between 'enum main()::Gender'
and 'enum main()::Color' [-Wenum-compare]
     if (gender == color)                ^

Enum Class

C++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped. Class enum doesn’t allow implicit conversion to int, and also doesn’t compare enumerators from different enumerations.
To define enum class we use class keyword after enum keyword. 
Syntax: 

// Declaration
enum class EnumName{ Value1, Value2, ... ValueN};

// Initialisation
EnumName ObjectName = EnumName::Value;

Example: 

// Declaration
enum class Color{ Red, Green, Blue};

// Initialisation
Color col = Color::Red;

Below is an implementation to show Enum Class
 

// C++ program to demonstrate working

// of Enum Classes



#include <iostream>

using namespace std;



int main()

{



    enum class Color { Red,

                       Green,

                       Blue };

    enum class Color2 { Red,

                        Black,

                        White };

    enum class People { Good,

                        Bad };



    // An enum value can now be used

    // to create variables

    int Green = 10;



    // Instantiating the Enum Class

    Color x = Color::Green;



    // Comparison now is completely type-safe

    if (x == Color::Red)

        cout << "It's Red\n";

    else

        cout << "It's not Red\n";



    People p = People::Good;



    if (p == People::Bad)

        cout << "Bad people\n";

    else

        cout << "Good people\n";



    // gives an error

    // if(x == p)

    // cout<<"red is equal to good";



    // won't work as there is no

    // implicit conversion to int

    // cout<< x;



    cout << int(x);



    return 0;

}

Output

It's not Red
Good people
1

Enumerated types declared within the enum class also have more control over their underlying type; it may be any integral data type, such as char, short or unsigned int, which essentially serves to determines the size of the type.

This is specified by a colon and underlying type following the enumerated type:

eg: enum class eyecolor : char {char,green,blue};
Here eyecolor is a distinct type with the same size as a char (1 byte).

#include <iostream>

using namespace std;

enum rainbow{

    violet,

    indigo,

    blue,

    green,yellow,orange,red

}colors;

enum class eyecolor:char{

    blue,green,brown

}eye;

int main() {

    cout<<"size of enum rainbow variable: "<<sizeof(colors)<<endl;

    cout<<"size of enum class eyecolor variable:"<<sizeof(eye)<<endl;

    return 0;

}

Output

size of enum rainbow variable: 4
size of enum class eyecolor variable:1

Reference: Enumeration declaration - cppreference.com
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值