0

我正在尝试重载 >> 运算符以读取单个(使用创建的enum Symbol {e,a,b,c,d};)符号:

istream & operator >> (istream & is, Symbol & sym) {
  Symbol Arr[]={e,a,b,c,d};
  char ch;
  is>>ch;
  if (strchr("eabcd",ch))
    sym=Arr[ch-'e'];
      else {
        is.unget(); 
        is.setstate(ios::failbit);
      }
  return is;
}

但这会读取一些垃圾(数字)而不是我正在寻找的内容,导致尝试使用 << 重载打印它时出现分段错误,我做错了什么?编辑:哦,当然我using namespace std;在开始时确实添加了,与包含iostreamand相同cstring

4

2 回答 2

1

这里有一些问题。首先,让我们修复你的支撑。只是总是使用大括号。很难看出什么与什么对齐:

istream & operator >> (istream & is, Symbol & sym) {
    Symbol Arr[]={e,a,b,c,d};
    char ch;
    is>>ch;
    if (strchr("eabcd",ch)) {
        sym=Arr[ch-'e'];
    }
    else {
        is.unget(); 
        is.setstate(ios::failbit);
    }
    return is;
}

好,很好。现在,如果用户输入类似'a'. strchr成功,然后你做sym = Arr[ch - 'e']。但ch - 'e'在这种情况下是-4。那是某处完全随机的内存,所以你得到了垃圾。要实际使用strchr,您需要执行以下操作:

const char* options = "eabcd";
if (const char* p = strchr(options, ch)) {
    sym = Arr[p - options];
}

但这有点可怕。我建议只使用一个开关:

switch (ch) {
    case 'e': sym = e; break;
    case 'a': sym = a; break;
    ...
    default:
        is.unget();
        is.setstate(ios::failbit);
}

另外is >> ch可能会失败,而您没有检查。你应该:

istream& operator>>(istream& is, Symbol& sym) {
    char ch;
    if (is >> ch) {
        switch(ch) { ... }
    }
    return is;
}
于 2016-03-18T21:44:31.680 回答
0

如果ch'a'ch - 'e'(97 - 101) 将是一个负数 (-4),这将导致访问数组Arr越界。这会导致未定义的行为。

您拥有符号的方式,您需要使用一个switch语句:

switch (ch)
{
   case 'a':
      sym = a;
      break;

   case 'b':
      sym = b;
      break;

   case 'c':
      sym = c;
      break;

   case 'd':
      sym = d;
      break;

   case 'e':
      sym = e;
      break;

   default:
     // Nothing to do
     break;
}

如果要使用Arr,则需要定义Arr为:

 Symbol Arr[]={a,b,c,d,e};

然后,您可以按如下方式访问数组并避免该switch语句:

sym=Arr[ch-'a'];  // ch - 'a' is 0 when ch is 'a'
                  // ch - 'a' is 4 when ch is 'e'.
于 2016-03-18T21:44:25.553 回答