C 操作员在枚举类中的过载

c++ operator overload in an enum class

本文关键字:操作员 枚举      更新时间:2023-10-16

因此,我正在使用C 编写游戏,在我的教程状态下,我有不同的步骤,用户可以通过,解释了游戏的工作原理。我想增加执行某个操作后用户处于哪个步骤。(鼠标单击)。我尝试使++运算符超载,但我遇到了一个错误说binary '++': 'STEPS' does not define this operator or a conversion to a type acceptable to the predefined operator。我正在使用Visual Studio,它的错误代码C2676

我的枚举课程设置如下:

enum class STEPS
{
    ONE,
    TWO,
    END_OF_LIST
};
STEPS& operator++(STEPS& s)
{
    s = staic_cast<STEPS>(static_cast<int>(s) + 1);
    if (s == STEPS::END_OF_LIST)
    {
        s = static_cast<STEPS>(static_cast<int>(s) - 1);
    }
    return s;
}

在我的教程状态类的更新功能中,我检查鼠标是否单击。如果是我要增加步骤。

//这是在标题中定义的,并将其设置为初始化时的步骤::一个 STEPS steps;

TutorialState::Update()
{
    // If mouse was clicked
    if (mouse.Left())
    {
        steps++; // this is giving me an error.
    }
}
STEPS& operator++(STEPS& s);

适用于++step

对于step++,您需要

STEPS operator++(STEPS& s, int) { auto res = s; ++s; return res; }

已选择使用额外的参数 int来区分预增量运算符。

您可以阅读http://en.cppreference.com/w/cpp/language/operator_incdec有关更多详细信息。