在我的程序中,我想使用
enum class
象征性地表示一些音符时长。符号枚举名称表示的数值是双精度数,但是枚举仅适用于整数,因此我想到对值使用定点表示,然后在从其他地方的 getter 方法返回枚举时进行除法程序。为此,我使用了一个结构体,但是由于结构体值不是文字,因此我无法在枚举中使用结构体中的值。编译器抱怨“表达式必须具有常量值”。
const double fp_multiplier = 10000.00; //utility const for fixed point conversion
// fixed point representations of note values
struct {
const int whole = (int)(1.0*fp_multiplier);
const int half = (int)(0.5*fp_multiplier);
const int eigth = (int)(0.125*fp_multiplier);
const int sixteenth = (int)(0.0625*fp_multiplier);
const int dotted_eigth = (int)((eigth + 0.5*eigth)*fp_multiplier);
const int dotted_sixteenth = (int)((sixteenth + 0.5*sixteenth)*fp_multiplier);
} NoteValues;
enum class NoteValue {
whole = NoteValues.whole, //not allowed
half = NoteValues.half,
eigth = NoteValues.eigth,
sixteenth = NoteValues.sixteenth,
dotted_eigth = NoteValues.dotted_eigth,
dotted_sixteenth = NoteValues.dotted_sixteenth,
};
据我了解这是不允许的,因为
NoteValues.whole
不是结构的实例?它不是文字或常量值(在本例中常量与 const
关键字不同且无关)。如何以满足编译器的方式将枚举值分配给结构中的值,或者是否有其他更好的方法来实现此目的?我特别希望能够有一个注释值的枚举。
将对象转换为类型,使成员静态,并使用类访问语法。
您还需要将
fp_multiplier
变成 constexpr
。
constexpr double fp_multiplier = 10000.00;
struct NoteValues{
static const int whole = (int)(1.0*fp_multiplier);
static const int half = (int)(0.5*fp_multiplier);
static const int eigth = (int)(0.125*fp_multiplier);
static const int sixteenth = (int)(0.0625*fp_multiplier);
static const int dotted_eigth = (int)((eigth + 0.5*eigth)*fp_multiplier);
static const int dotted_sixteenth = (int)((sixteenth + 0.5*sixteenth)*fp_multiplier);
};
enum class NoteValue {
whole = NoteValues::whole, //not allowed
half = NoteValues::half,
eigth = NoteValues::eigth,
sixteenth = NoteValues::sixteenth,
dotted_eigth = NoteValues::dotted_eigth,
dotted_sixteenth = NoteValues::dotted_sixteenth,
};