为什么我不能在 switch 中使用非整数类型

vla*_*378 4 c++ class switch-statement implicit-conversion

因为如果我定义operator==然后比较将是可能的:

class My
{
    int x;
    // ...
public:
    My(int);

    bool operator==(const My & y);
        // ...
};

//...

My one = 1;
switch (one)
{
    case 1 : // anything

    default : // ...
}
Run Code Online (Sandbox Code Playgroud)

但它仅适用于整数类型。为什么?

Dre*_*ann 6

BCPL 和 C 语言实现switchswitchon在 BCPL 中)作为汇编分支表的更高级别实现。

分支表是 if/else 链的一种非常有效的实现,它使用单个整数来索引地址数组(或地址偏移量)。程序控制跳转到表中指定索引处的地址。

switch 需要整数类型(或隐式转换为整数的类型),因为数组索引需要整数类型。

C++ 继承了与 C++ 相同的语言特性,switch而没有进行重大更改。

这将是可能重新定义语言实现switch使用operator ==,但同样的行为已经可以实现为的if / else链。