C ++,三元运算符,std :: cout [英] C++, ternary operator, std::cout

查看:98
本文介绍了C ++,三元运算符,std :: cout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用C ++使用三元运算符编写以下条件

How to write the following condition with a ternary operator using C++

int condition1, condition2, condition3;
int / double result; //int or double
....
std::cout << ( condition1: result1 : "Error" ) 
          << ( condition2: result2 : "Error" )
          << ( condition3: result3 : "Error")...;


推荐答案

取决于是什么类型result1,result2 等。

expressionC吗? expression1:expression2 对所有类型的 expression1 expression2 均无效。粗略地说,它们必须可以转换为通用类型(可以在标准中阅读确切的规则和例外)。现在,如果 result 是字符串,则可以这样操作:

expressionC ? expression1 : expression2 isn't valid for all types of expression1 and expression2. They must necessarily be convertible to a common type, roughly speaking (exact rules and exceptions can be read in the standard). Now, if results are strings, then you do it like this:

std::cout << ( condition1 ? result1 : "Error" ) 
                         ^^^
          << ( condition2 ? result2 : "Error") 
                         ^^^
          << etc.

但是,例如,如果结果是整数,则不能这样做。

But if results are integers, for example, you can't do it.

HTH

这篇关于C ++,三元运算符,std :: cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆