我试图重载>>操作符以读取单个符号(用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;,包括iostream和cstring。
发布于 2016-03-18 21:44:31
这里有一些地方不对劲。首先,让我们修复你的支撑。总是用牙套。很难看出什么和什么是一致的:
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-18 21:44:25
如果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'.https://stackoverflow.com/questions/36094686
复制相似问题