在编写复杂的逻辑检查时,我无法理解 C++ 中的运算符分组。 基本上,我只关心这段代码是否:
int getIndex(int i) throw(Exception) {
return (i >= 0 && i < length) ? array[i] : throw IndexOutOfBoundsException();
}
和这个一样:
int getIndex(int i) throw(Exception) {
return i >= 0 && i < length ? array[i] : throw IndexOutOfBoundsException();
}
此外,我不确定嵌套三元运算符时有什么限制,因为我想做这样的事情:
int getIndex(int i) throw(Exception) {
return (i >= 0 && i < capacity) ? ((i < length) ? (array[i]) : (throw IndexOfEmptyFieldException(); ) : (throw IndexOutOfBoundsException(); ))
}
但是(当然)我希望它能正常工作并且可读。
如果您认为这是使用三元运算符的坏例子,我应该只使用if/else
还是其他一些方法并避免在未来?
最佳答案
? :
的优先级低于 &&
,所以是的,您的前两个示例是等效的。
至于你的第三个例子,我会写成
int getIndex(int i) throw(Exception) {
return
i < 0 || i >= capacity ? throw IndexOutOfBoundsException() :
i >= length ? throw IndexOfEmptyFieldException() :
array[i]
;
}
我认为“嵌套”条件运算符只要“序列化”就很好,即它们构成相当于 if/elsif/else 链的内容。
虽然这个特殊情况值得商榷,因为实际上只有一个分支返回一个值。其他两个只是抛出一个异常,作为单独的语句通常更好:抛出异常作为表达式没有实际值(value);它仅用于其副作用。
关于c++ - 三元运算符 : exception throwing and nesting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33064615/