【发布时间】:2016-01-08 22:59:04
【问题描述】:
在编写复杂的逻辑检查时,我无法理解 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
-
@JoachimPileborg 该标准特别允许将 throw 表达式放在条件(三元)运算符中,在这种情况下,结果具有另一个分支的类型。
标签: c++ ternary-operator operator-precedence throw