问题描述
因为如果我定义 operator==
那么比较将是可能的:
Cause if I define the operator==
then comparison will be possible:
class My
{
int x;
// ...
public:
My(int);
bool operator==(const My & y);
// ...
};
//...
My one = 1;
switch (one)
{
case 1 : // anything
default : // ...
}
但这仅适用于整数类型.为什么?
But it's possible only for integer types. Why?
推荐答案
BCPL 和 C 语言实现了 switch
(BCPL 中的 switchon
)作为更高级别的实现装配分支表.
The BCPL and C languages implemented switch
(switchon
in BCPL) as a higher-level implementation of an assembly branch table.
分支表是 if/else 链的一种非常有效的实现,它使用单个整数来索引地址数组(或地址偏移量).程序控制跳转到表中指定索引处的地址.
A branch table is a very efficient implementation of an if/else chain that uses a single integer to index into an array of addresses (or address offsets). Program control jumps to the address at the specified index of the table.
switch
需要整数类型(或隐式转换为整数的类型),因为数组索引需要整数类型.
switch
requires an integer type (or a type implicitly convertible to an integer) because array-indexing requires an integer type.
C++ 继承了 switch
的相同语言属性,而没有进行重大更改.
C++ inherited the same language properties of switch
without making significant changes.
可能使用operator ==
重新定义实现switch
的语言,但同样的行为已经可以作为if/else 链.
It would be possible to redefine the language to implement switch
using operator ==
, but that same behavior can already be implemented as an if/else chain.
这篇关于为什么我不能在 switch 中使用非整数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!