【问题标题】:Why can't I use non-integral types with switch [duplicate]为什么我不能使用带有开关的非整数类型 [重复]
【发布时间】:2015-07-15 21:33:57
【问题描述】:

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

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

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

//...

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

    default : // ...
}

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

【问题讨论】:

  • 这是语言的规则
  • 因为语言不允许。
  • 我喜欢它。但这是什么原因呢?

标签: c++ class switch-statement implicit-conversion


【解决方案1】:

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

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

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

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

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

【讨论】:

【解决方案2】:

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

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

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!

【讨论】:

    【解决方案3】:

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

    operator int() const { return x; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多