关于枚举的一些知识点

《c++程序设计语言(第四版)》8.4章节

1、枚举分成两种enum class和enum,前者枚举值不会隐式转换成其他类型,后者值会转成整数。一般应该使用前者。

2、枚举值类型一般是int,如果认为int类型浪费空间也可以显示地指定其他类型:

enum class color:char
{
    red,
    green,
    yellow
};

3、枚举的位运算:

enum class color:char
{
    red = 5,
    green = 6,
    yellow = 7
};

constexpr color operator |(color c1,color c2)
{
    return static_cast<color>(static_cast<int>(c1) | static_cast<int>(c2));
}

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    color c1 = color::red;
    color c2 = color::green;
    color c3 = c1 | c2;
    debug static_cast<int>(c3) << (c3 == color::yellow);// 5 | 6 = 7
}

4、枚举的sizeof()的值等于枚举值类型的(int \ char)sizeof()的值。

5、如果枚举不必用来声明对象,可以使用匿名枚举:

enum color:int
{
    red = 666,
    green = 999,
    yellow = 444
};

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    int c = red;
    debug c;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的枚举类型是一种特殊的类,它可以用于定义一组常量。在Java中,枚举类型的定义方式比较简单,主要有以下几个知识点: 1. 枚举类型的定义:使用enum关键字定义枚举类型枚举类型中的每个枚举常量都是该类型的一个实例。例如: ``` enum Color { RED, GREEN, BLUE } ``` 2. 枚举常量的使用:枚举常量可以直接使用枚举类型的名称进行限定,也可以使用枚举常量的名称进行限定。例如: ``` Color c1 = Color.RED; Color c2 = Color.valueOf("GREEN"); ``` 3. 枚举类型的方法:枚举类型可以定义方法,这些方法可以在枚举常量中进行调用。例如: ``` enum Color { RED, GREEN, BLUE; public void printValue() { System.out.println(this.name() + ": " + this.ordinal()); } } Color.RED.printValue(); // 输出:RED: 0 Color.GREEN.printValue(); // 输出:GREEN: 1 Color.BLUE.printValue(); // 输出:BLUE: 2 ``` 4. 枚举类型的属性:枚举类型可以定义属性,这些属性可以在枚举常量中进行调用。例如: ``` enum Color { RED("#FF0000"), GREEN("#00FF00"), BLUE("#0000FF"); private String value; Color(String value) { this.value = value; } public String getValue() { return value; } } String redValue = Color.RED.getValue(); // 输出:#FF0000 ``` 5. 枚举类型的实现接口:枚举类型可以实现接口,从而获得接口的所有方法。例如: ``` interface Printable { void print(); } enum Color implements Printable { RED, GREEN, BLUE; public void print() { System.out.println(this.name()); } } Color.RED.print(); // 输出:RED ``` 总之,枚举类型是Java中非常有用的一种类型,可以用于定义一组常量,提高程序的可读性和健壮性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值