0
在编写复杂逻辑检查时,我无法理解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
或一些其他的方法,避免结构像这样的未来?
使用三元表达式有两个问题,第一个也是最明显的是可读性/可维护性方面。第二个是表达式的两个分支必须返回相同的类型,而不是。事实上,你的一个分支根本不会返回。 –
@JoachimPileborg它编译,虽然我没有尝试运行它。此外,此异常的catch块会终止程序。 –
嵌套三元组如何增加可读性?如果存在多个条件,我肯定会更喜欢if/else – user463035818