没有正确使用操作员'?'?
Not using operator '?' properly?
本文关键字:操作员 更新时间:2023-10-16
所以我有函数返回一个整数以及它的一些最大值和最小值。我想在最后用漂亮干净的单行词来做:
(freq>max_freq) ? return max_freq : ((freq<min_freq) ? return min_freq : return freq);
但我得到的是
posplot.hh:238:21: error: expected primary-expression before ‘return’
(freq>max_freq) ? return max_freq : ((freq<min_freq) ? return min_freq : return freq);}
^
posplot.hh:238:21: error: expected ‘:’ before ‘return’
posplot.hh:238:21: error: expected primary-expression before ‘return’
posplot.hh:238:21: error: expected ‘;’ before ‘return’
那么,这是因为在这里使用 return 是一件愚蠢的事情,我应该以其他方式让它工作,或者它可以工作但我搞砸了?我很好奇,因为我想我已经使用"?"运算符作为更整洁的 if-else 用于很多东西,而且它总是工作正常。有人可以解释为什么会发生这种情况吗?
您需要在
三元运算符之前移动返回:
return (freq>max_freq) ? max_freq : ((freq<min_freq) ? min_freq : freq);
基本上,三元运算符应该在每个分支上计算为单个值(这意味着它需要 3 个表达式,并且您正在创建一个表达式和两个语句,因为return
创建一个语句)。
条件运算符的操作数(与大多数其他运算符一样)必须是表达式而不是语句,因此它们不能是返回语句。
条件表达式本身有一个值:所选操作数的值。评估并返回它:
return (freq>max_freq) ? max_freq : ((freq<min_freq) ? min_freq : freq);
? 运算符可用于表达式中。 返回是一个语句
您的单行代码可能如下所示:
return (freq>max_freq ? max_freq : (freq<min_freq ? min_freq : freq));
相关文章:
- <<操作员在下面的行中工作
- C++ 与操作员不匹配<<
- 操作员C++的模棱两可的过载
- C++中>>操作员过载时出现问题?
- NaN 上的宇宙飞船操作员
- 比根<操作员
- SFINAE不能防止模棱两可的操作员过载吗?
- 什么是现实中的"endl"(或任何输出操纵器)?它是如何实现的,它如何与操作员<<一起工
- 为什么"delete"操作员给我访问权限冲突
- 为什么使操作员成为新的专用会打破 std::shared_ptr?
- 在这种情况下是私有的吗?试图使操作员<<过载
- C++操作员过载>>
- 是否有 C++20 浮点数的包装器,使我能够默认宇宙飞船操作员?
- 与异常处理程序中的操作员<<不匹配
- 复印作业操作员说明
- 友谊和操作员+=重载
- >操作员在比较两个C++容器时会怎么做?
- 与操作员比较两个计时时间点
- C++操作员订单评估
- 如何强制新操作员根据我的需要解释语句