首页 > 解决方案 > 带有类的 switch 语句

问题描述

我们目前正在我的计算机科学课上学习课程。今天,老师向我们介绍了 Switch Statements,我有一个他不确定的问题:

标签: c++

解决方案


正如您所说的那样:不。但是可以设计一个兼容的类 witch switch。这是一个使用整数的准系统包装类的示例:

// Only possible in C++11 and newer.
class Integer
{
public:
    constexpr explicit Integer(int p) : m_payload(p) {}     // (1)
    constexpr operator int() const { return m_payload; }    // (2)

private:
    int m_payload;
};


int main()
{
    // For simplicity. This could be a user input or some other value
    // determined when running the program.
    Integer five(5);

    switch (five) {  // (4)
        case Integer(5):  // (3)
            return 0;
        default:
            return 1;
    }
}

我将掩盖很多更精细的细节。代码的作用是这样的:

  • switch在这种情况下,在第 (4) 行中计算的值five必须是类整数值或可隐式转换为类整数值。这就是operator int()(2) 所做的——它被称为转换运算符。
  • switch的cases 必须是常量整数表达式,即它们必须评估为类似整数的值,并且评估必须在编译时是可能的。要使第 (3) 行工作,以下所有条件都必须为真:
    • Integer对象必须能够在编译时创建。这是由第 (1) 行中的 constexpr 构造函数提供的。这里constexpr是关键。
    • 必须使用在编译时实际已知的值来创建对象。这是第 (3) 行中的文字5。您无法运行程序、向用户查询整数并使用该用户输入而不是5. 毕竟,编译器无法预测用户的输入。
    • Integer对象必须在编译时隐式转换为类似整数的。这是由constexprin like (2) 提供的。

总结一下:是的,你可以设计自己的类来兼容switch. 但是有相当严格的限制,它与operator==().


推荐阅读