c++ - 带有类的 switch 语句
问题描述
我们目前正在我的计算机科学课上学习课程。今天,老师向我们介绍了 Switch Statements,我有一个他不确定的问题:
- 如果我们重载 == 运算符,是否可以将 switch 语句与类一起使用?
解决方案
正如您所说的那样:不。但是可以设计一个兼容的类 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的
case
s 必须是常量整数表达式,即它们必须评估为类似整数的值,并且评估必须在编译时是可能的。要使第 (3) 行工作,以下所有条件都必须为真:Integer
对象必须能够在编译时创建。这是由第 (1) 行中的 constexpr 构造函数提供的。这里constexpr
是关键。- 必须使用在编译时实际已知的值来创建对象。这是第 (3) 行中的文字
5
。您无法运行程序、向用户查询整数并使用该用户输入而不是5
. 毕竟,编译器无法预测用户的输入。 Integer
对象必须在编译时隐式转换为类似整数的值。这是由constexpr
in like (2) 提供的。
总结一下:是的,你可以设计自己的类来兼容switch
. 但是有相当严格的限制,它与operator==()
.
推荐阅读
- azure-devops - 是否可以使用 Azure DevOps 复制具有例外规则的文件?
- android - 基于按钮单击将不同的数据重新填充到 RecyclerView
- typescript - 配置 Typescript 编译器
- java - 你如何在 android studio 中的 Fragment 上编码
- html - 网页上托管的目录的url被点击时,默认模板是如何创建的?
- laravel - 动态自定义字段:JSON、Pivot、morphToMany?
- powershell - How to execute .exe tool with argument using Powershell script?
- log4j2 - 更改 log4j2 日志条目的级别
- ios - Play background music for 24 hours (sleep music app)
- sql-server - 如何根据函数中的条件返回值?SQL 服务器