为什么这个程序没有输出什么?

viv*_*ain -5 c++

#include <iostream>
using namespace std;

int main()
{
   int test = 0;
   cout << (test ? "A String" : 0) << endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 9

三元?:运算符要求两个输出操作数要么是相同的数据类型,要么至少可以转换为公共数据类型.A char*不能隐式转换为a int,但0文字可以隐式转换为a char*.

试试这个:

#include <iostream>

int main()
{
   int test = 0;
   std::cout << ((test) ? "A String" : "") << std::endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

要么:

#include <iostream>

int main()
{
   int test = 0;
   std::cout << ((test) ? "A String" : (char*)0) << std::endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果你想0test0 时实际输出,那么你必须这样做:

#include <iostream>

int main()
{
   int test = 0;
   std::cout << ((test) ? "A String" : "0") << std::endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

否则,请删除?:运算符,因为您无法使用它来混合不同的不兼容数据类型以进行输出:

#include <iostream>

int main()
{
   int test = 0;
   if (test)
       std::cout << "A String";
   else
       std::cout << 0;
   std::cout << std::endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 该程序编译得很好.我认为OP期望输出为"0". (4认同)
  • 三元运算符不*要求两个输出表达式具有相同的数据类型,但如果两者不同,它将把它们转换为公共数据类型. (2认同)