任何可以用三元组完成的东西,但不能用别的东西 [英] anything whcih can be done with ternary but not with if else
问题描述
HI,
是否有任何情况可由三元运营商处理,但
不是if else阻止?
谢谢
Keshav
Is there any situation which can be handled by ternary operator but
not with if else blocks?
Thanks
Keshav
推荐答案
gu ********** @ gmail.com 写道:
gu**********@gmail.com wrote:
HI,
有什么情况吗可以由三元运算符处理但是不用if else块吗?
Is there any situation which can be handled by ternary operator but
not with if else blocks?
class Foo
{
public:
Foo(bool b)
:x_(b?42:7)
{
}
私人:
const int x_;
};
class Foo
{
public:
Foo(bool b)
: x_(b ? 42 : 7)
{
}
private:
const int x_;
};
Rolf Magnus写道:
Rolf Magnus wrote:
gu ********** @ gmail.com 写道:
gu**********@gmail.com wrote:
HI,
是否有任何情况可以由三元运营商处理,但
不是if else阻止?
Is there any situation which can be handled by ternary operator but
not with if else blocks?
cl屁股Foo
{
公开:
Foo(bool b)
:x_(b? 42:7)
{
}
私人:
const int x_;
};
class Foo
{
public:
Foo(bool b)
: x_(b ? 42 : 7)
{
}
private:
const int x_;
};
并有条件地分配常量。比较:
void Foo(const bool b)
{
const int i = b? 1:2;
// ...
}
void Bar(const bool b)
{
//我不能是const
int i = 0;
if(b)
{
i = 1;
}
else
{
i = 2 ;
}
// ...
}
干杯! --M
And conditionally assigning constants in general. Compare:
void Foo( const bool b )
{
const int i = b ? 1 : 2;
// ...
}
void Bar( const bool b )
{
// i cannot be const
int i = 0;
if( b )
{
i = 1;
}
else
{
i = 2;
}
// ...
}
Cheers! --M
< gu ********** @ gmail.com>在消息中写道
news:11 ********************* @ g14g2000cwa.googlegro ups.com
<gu**********@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com
HI,
是否有任何情况可由三元运营商处理,但
不是if else块?
谢谢
Keshav
Is there any situation which can be handled by ternary operator but
not with if else blocks?
Thanks
Keshav
bool b;
int x,y;
//东西设置b,x和y
int& ref = b? x,y;
请注意,如果(b)
int& b,你可以这样做
ref = x;
else
int& ref = y;
但参考范围仅限于if-else
条件的正文。你不能通过在
if语句之前声明引用来解决这个问题,因为引用必须在
声明时初始化。
-
John Carson
bool b;
int x, y;
// stuff setting b, x and y
int & ref = b ? x, y;
Note that you can do
if(b)
int & ref = x;
else
int & ref = y;
but the scope of the reference is limited to the body of the if-else
conditions. You can''t get around this by declaring the reference before the
if statement because a reference must be initialised at its point of
declaration.
--
John Carson
这篇关于任何可以用三元组完成的东西,但不能用别的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!