Java中实现枚举和C++中使用数组length
来自:《代码大全》
在Java没有C++中的枚举类型,有时候会很不方便,下面的方法可以实现
1 2 3 4 5 6 7 8 |
class Country { private Country() {} public static final Country China = new Country(); public static final Country England = new Country(); public static final Country France = new Country(); public static final Country Germany = new Country(); public static final Country India = new Country(); } |
这种特殊的创建枚举的方法是类型安全的(type safe),因为编译器会检查非法的赋值
1 |
Output output = Country.England; //编译不通过 |
在C++中,数组不是对象,更无法使用Java中所具有的数组length,这个可以用宏实现
1 |
#define ARRAY_LENGTH(x) (sizeof(x)/sizeof(x[0])) |
这个方法也使用于各维数组
都很巧妙是吧
Trackback from your site.