3

在 Lua 中,你可以这样做:

foo = a and b or c and d or e

这相当于(至少我很确定它相当于):

local foo = nil
if a then
foo = b
elseif c then
foo = d
else
foo = e
end

在 C++ 中是否有与此等效或类似的东西?

4

5 回答 5

6

I guess this is what you want:

foo = a ? b : (c ? d : e );
于 2012-05-26T09:53:46.370 回答
5

三元运算符。它具有有趣的优先级,因此始终将其括起来是一个好习惯。

bool foo = ( a ? b : ( c ? d : e ) )

Note that this only works if b, d, and e can reduce to the same type. If a is a double, d is a float and e is an int, your result will always be cast to a double.

于 2012-05-26T09:53:42.410 回答
2

您可以使用三元运算符?:

foo = a ? b : c ? d : e;
于 2012-05-26T09:53:29.040 回答
1

Not really. The main reason this works in Lua is because of dynamic typing- in C++ you could never really make it work. The closest you can get is the ternary operator, but it has srs limitations.

于 2012-05-26T09:56:46.463 回答
-3

&&CC++中使用for and then并使用||for or else

将三元?:用于条件表达式

于 2012-05-26T09:53:36.930 回答