Java Enum如何与C ++和传统Enum不同? [英] How Java Enum is different then C++ and othere conventional Enum?
问题描述
在java枚举中,我们从java 1.5获取的枚举与C ++和其他常规枚举类型不同。是复杂对象,而在C ++中,每个枚举对象都与单个整数值相关联。在java中,您可以使用与单个枚举值相关联的几个属性:
枚举MyCategory {
SPORT类别,sport.png),
新闻(新闻类别,news.jpg);
private String description;
private String iconPath;
private MyCategory(String description,String iconPath){
this.description = description;
this.iconPath = iconPath;
}
public String getDescription(){
return description;
}
public String getIconPath(){
return iconPath;
}
}
此外,在java中,您可以开关
仅数字类型,字符串和枚举。然而,我无法将传统的枚举整体概括为...
编辑 java枚举可以做的另外一件事是声明每值操作(取自 java教程):
public enum Operation {
PLUS {double eval(double x,double y){return x + y; }},
MINUS {double eval(double x,double y){return x - y; }},
TIMES {double eval(double x,double y){return x * y; }},
DIVIDE {double eval(double x,double y){return x / y; }};
//做这个常数代表的算术运算
abstract double eval(double x,double y);
}
How the enum that we get from java 1.5 is different from C++ and other conventional Enum Type.
In java enums are complex objects, whilst in C++ every enum object is associated with a single integer value. In java you can have several attributes associated with a single enum value:
enum MyCategory {
SPORT("The sport category", "sport.png"),
NEWS("the news category", "news.jpg");
private String description;
private String iconPath;
private MyCategory(String description, String iconPath) {
this.description = description;
this.iconPath = iconPath;
}
public String getDescription() {
return description;
}
public String getIconPath() {
return iconPath;
}
}
Furthermore in java you can switch
only Number types, Strings and enums. However I can not generalize the conventional enums as a whole...
EDIT One more thing the java enums can do is declare per-value operation (taken from the java tutorial):
public enum Operation {
PLUS { double eval(double x, double y) { return x + y; } },
MINUS { double eval(double x, double y) { return x - y; } },
TIMES { double eval(double x, double y) { return x * y; } },
DIVIDE { double eval(double x, double y) { return x / y; } };
// Do arithmetic op represented by this constant
abstract double eval(double x, double y);
}
这篇关于Java Enum如何与C ++和传统Enum不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!