为什么我不能将非整数类型与开关一起使用

Why can't I use non-integral types with switch

因为如果我定义 operator== 则可以进行比较:

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

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

//...

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

    default : // ...
}

但这只适用于整数类型。为什么?

BCPL 和 C 语言实现了 switch(BCPL 中的 switchon)作为 assembly branch table.

的更高级实现

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

的指定索引处的地址

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

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

可能使用operator ==重新定义语言来实现switch,但同样的行为已经可以实现为[=33] =]链.

您可以在 switch 语句中使用 类。

根据C++标准(6.4.2 switch语句):

2 The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 4) to an integral or enumeration type.

这是一个演示程序

#include <iostream>

class A
{
    int x;

public:
    A( int x ) : x( x ) {}

    operator int() const { return x; }
};

int main()
{
    A a( 2 );

    switch ( a )
    {
        case 1:
            std::cout << "past by" << std::endl;
            break;
        case 2:
            std::cout << "Bingo!" << std::endl;
            break;
    }            
}

程序输出为

Bingo!

您可以将 implicit conversion operator 添加到您的 class 以实现此目的:

operator int() const { return x; }