c++ - 用 cout 打印出 bool 选项

标签 c++

我知道如果你的 bool 函数只打印出一些文本,有两种打印结果的方法。一个非常简单,像这样:

#include <iostream> 

using namespace std; 

bool function(int x) 
{ 
   int y=5; 
   return x==y; 
} 

int main(void) 
{ 
   int a; 
   cin >> a; 
   if(function(a))
      cout << "Equal to 5"; 
   else
      cout << "Not equal to 5"; 
 }

我曾经知道其他方法可以在同一行中使用 cout 和 bool 在一行中打印出一些“消息”,但以下解决方案无法解决问题。这有什么问题?

 cout << function(a) ? "Equal" : "Not equal"; 

我收到通知,调用函数的函数将始终返回 true,这很奇怪。

最佳答案

根据您的编译器,它可能会发出警告,准确说明问题所在。

main.cpp:15:21: warning: operator '?:' has lower precedence than '<<'; '<<' will be evaluated first [-Wparentheses]
cout << function(a) ? "Equal" : "Not equal"; 
~~~~~~~~~~~~~~~~~~~ ^
main.cpp:15:21: note: place parentheses around the '<<' expression to silence this warning
cout << function(a) ? "Equal" : "Not equal"; 
                    ^
(                  )
main.cpp:15:21: note: place parentheses around the '?:' expression to evaluate it first
cout << function(a) ? "Equal" : "Not equal"; 
main.cpp:15:26: warning: expression result unused [-Wunused-value]
   cout << function(a) ? "Equal" : "Not equal"; 

作为@The Paramagnetic Croissant说,将其括在括号中。

cout << (function(a) ? "Equal" : "Not equal"); 

根据 @WhozCraig's comment , 一个解释是顺序。正如警告所说,<<首先进行评估,结果为 (cout << function(a)) ? "Equal : "Not Equal"; .这将返回“等于”(或“不等于”,无关紧要),从而导致随后的“表达式结果未使用”警告。

关于c++ - 用 cout 打印出 bool 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26596509/

相关文章:

c++ - FillConsoleOutputCharacterW() C++ 错误

c++ - 程序检查以查看用户编号是否存储在 C++ 中的数组中

c++ - torrent 文件使用什么类型的编码以及如何附加跟踪器?

c++ - OpenCV 2.3 SURF关键点倍频程永远不等于0

c++ - 如何将 SendMessage() 发送到在另一个线程上创建的窗口?

c++ - 优先级队列比较器[C++]

java - 在基类构造函数中调用虚方法

c++ - 为什么派生类必须重新定义重写的基类方法

c++ - 在编译期间包含未使用的代码

c++ - 为什么我不能使用 "const string* sp = 0"在构造函数中初始化