为什么我不能使用“中断” C ++中的三元条件语句中的语句? [英] Why can't I use a "break" statement inside a ternary conditional statement in C++?
问题描述
Node是一个非常简单的类,只有一个构造函数和一些变量:一个名称(实际上只是一个char)和两个子节点指针,称为左和右。
我刚刚开始写一些需要删除最左边节点的代码,当我想到这个时,我很高兴:
Node * current = this-> root;
while(true)(current-> left!= nullptr)? current = current-> left:break;
看起来很简单:在无限循环中,检查当前是否有一个左边的孩子,如果是,将当前设置为该小孩,如果没有,则突破循环。这是一个很酷的小单线,不太可读。 (我已经评论了!)
嗯,我的编译器不喜欢它:
iterator.cpp:20:70:error:expected expression
while(true)(current-> left!= nullptr)? current = current-> left:break;
^
1生成错误。
此外,只要在while循环中抛出一些大括号,并将三元运算符移动到自己的行,帮助(不出意料)。我不得不把它变成一个if / else来编译器来接受它。
有人可以解释一下它是如何解释单行的,为什么它是对象? >
三元条件运算符是将多个表达式组合成较大表达式的运算符。 break
是一个语句,而不是一个表达式,因此它不能在三元条件表达式中使用。 / p>
尽管如此,您可以重写代码:
while (current-> left!= nullptr)current = current-> left;
希望这有帮助!
Node is a very simple class with a just a constructor and a few variables: a "name" (actually just a char) and two child Node pointers called "left" and "right".
I was just starting to write some code that needs to drop to the left-most node, and I was quite pleased when I came up with this:
Node *current = this->root;
while (true) (current->left != nullptr) ? current = current->left : break;
Seems simple enough: in an infinite loop, check to see if current has a left child, if so, set current to that left child, if not, break out of the loop. It's a cool little one-liner, not too unreadable. (And I commented it!)
Well, my compiler doesn't like it:
iterator.cpp:20:70: error: expected expression
while (true) (current->left != nullptr) ? current = current->left : break;
^
1 error generated.
Also, just throwing some braces into the while loop and moving the ternary operator to it's own line didn't help (unsurprisingly). I had to turn it into an if/else for the compiler to accept it.
Can someone explain how it's interpreting the one-liner and why it objects?
The ternary conditional operator is an operator that combines multiple expressions into a larger expression. break
is a statement and not an expression, so it can't be used inside a ternary conditional expression.
You could, though, rewrite your code like this:
while (current->left != nullptr) current = current->left;
Hope this helps!
这篇关于为什么我不能使用“中断” C ++中的三元条件语句中的语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!