gpt4 book ai didi

c++ - 带类的 Switch 语句

转载 作者:行者123 更新时间:2023-11-30 02:14:16 29 4
gpt4 key购买 nike

我们目前正在学习我的计算科学类(class)。今天老师给我们介绍了Switch Statements,我有以下问题他不太确定:

  • 如果我们重载 == 运算符,switch 语句可以与类一起使用吗?

最佳答案

正如您所说的问题:不。但是可以设计一个与 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——必须是一个类整数值或隐式可转换为类整数值(value)。这就是 operator int() (2) 所做的——它被称为转换运算符。
  • switch 的 case 必须是常量整数表达式,即它们必须求值为类似整数的值,并且求值必须可以在编译时进行。要使第 (3) 行起作用,必须满足以下所有条件:
    • Integer 对象必须能够在编译时创建。这是由第 (1) 行中的 constexpr 构造函数提供的。 constexpr 是这里的关键。
    • 必须使用在编译时实际已知的值创建对象。这是第 (3) 行中的文字 5。您无法运行您的程序、向用户查询整数并使用该用户输入而不是 5。毕竟,编译器无法预测用户的输入。
    • Integer 对象必须在编译时隐式转换为类整数值。这是由 (2) 中的 constexpr 提供的。

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

关于c++ - 带类的 Switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58246604/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com