为什么我不能使用带开关的非整数类型

时间:2015-07-15 21:33:58

标签: c++ switch-statement

如果我定义了operator==,那么可以进行比较:

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

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

//...

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

    default : // ...
}

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

3 个答案:

答案 0 :(得分:3)

BCPL和C语言实施switch(BCPL中为switchon)作为assembly branch table的更高级别实施。

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

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

C ++继承了switch的相同语言属性,但没有做出重大改变。

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

答案 1 :(得分:2)

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

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

  

2条件应为整数类型,枚举类型或类   类型。如果是类类型,则条件是上下文隐式的   转换(第4条)为整数或枚举类型。

这是一个示范程序

#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!

答案 2 :(得分:1)

您可以在课程中添加implicit conversion operator以使其成为可能:

operator int() const { return x; }