【问题标题】:c++ operator overload in an enum class枚举类中的 c++ 运算符重载
【发布时间】:2023-03-18 02:19:01
【问题描述】:

所以我正在使用 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::ONE STEPS steps;

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

【问题讨论】:

    标签: c++ class enums overloading operator-keyword


    【解决方案1】:
    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了解更多详情。

    【讨论】:

    • 嗯。我是重载运算符的新手,但我一定会检查一下。这一切对我来说仍然是模糊的。感谢您的快速回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2010-11-24
    相关资源
    最近更新 更多