在 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++ 中是否有与此等效或类似的东西?
I guess this is what you want:
foo = a ? b : (c ? d : e );
有三元运算符。它具有有趣的优先级,因此始终将其括起来是一个好习惯。
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
.
您可以使用三元运算符?:
foo = a ? b : c ? d : e;
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.
&&
在C或C++中使用for and then并使用||
for or else
将三元?:
用于条件表达式