简体   繁体   English

在C ++中必须使用条件表达式(?:)

[英]Where in C++ is Required to Use Conditional Expression (?:)

I have a book that teaches C++ programming. 我有一本教C ++编程的书。 In the book, it says "Conditional expressions can appear in some program locations where if…else statements cannot" The book doesn't specify where. 在书中,它说“条件表达式可以出现在某些程序位置,如果...... else语句不能”本书没有指明在哪里。 I was curious if someone can show me an example where you explicitly MUST use conditional statement and not if...else statement. 我很好奇是否有人可以给我看一个示例,其中您必须明确使用条件语句,而不是if ... else语句。

Thanks, 谢谢,

In general, where language expects an expression. 一般来说,语言需要表达式。 There are several cases where ?: operator cannot be easily replaced with if statement. 在几种情况下, ?:运算符不能轻易地替换为if语句。 It rarely occurs in practice, but it is possible. 它很少在实践中发生,但它是可能的。 For example: 例如:

const int x = (a > 0) ? a : 0; // (global) const/constexpr initialization

struct D: public B {
     D(int a)
         : B(a > 0 ? a : 0) // member initializer list
     { }
};

template<int x> struct A {
};
A<(a>0) ? a : 0> var; // template argument

A conditional expression is an expression, whereas an if-else is a statement. 条件表达式是表达式,而if-else是语句。 That means you can embed conditional expressions in other expressions, but you can't do that with if-else: 这意味着您可以在其他表达式中嵌入条件表达式,但不能使用if-else执行此操作:

// works
x = flag ? 5 : 6;

// meaningless nonsense
x = if (flag) 5 else 6;

You can always rewrite the code to use if-else, but it requires restructuring the logic a bit. 您可以随时重写代码以使用if-else,但它需要稍微重构逻辑。

You can use the ternary operator in an expression, not just on statements. 您可以在表达式中使用三元运算符,而不仅仅是语句。 For example, 例如,

bool foo;
if (bar)
    foo = false;
else
    foo = true;

can be shortened to 可以缩短为

bool foo = (bar)?false:true;

It's never necessary to perform an action, and just exists for convenience. 从来没有必要执行任何操作,只是为了方便而存在。

'根据某些表达式初始化常量变量'-https: //stackoverflow.com/a/3565387/3969164

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM