为什么我不能使用“中断"?C++ 中三元条件语句中的语句?

Node 是一个非常简单的类,只有一个构造函数和几个变量:一个名称"(实际上只是一个字符)和两个称为左"和右"的子节点指针.

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;

看起来很简单:在一个无限循环中,检查 current 是否有左孩子,如果有,则将 current 设置为那个左孩子,如果没有,则跳出循环.这是一个很酷的小单线,不太难读.(我评论了!)

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.

此外,仅在 while 循环中加入一些大括号并将三元运算符移动到它自己的行也无济于事(不出所料).我不得不把它变成一个 if/else 以便编译器接受它.

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?

推荐答案

三元条件运算符是一种将多个表达式组合成一个更大表达式的运算符.break 是一个语句而不是一个表达式,所以它不能在三元条件表达式中使用.

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;

希望这有帮助!

相关文章