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

时间:2013-12-30 19:17:45

标签: c++

#include <iostream>
using namespace std;

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

   return 0;
}

1 个答案:

答案 0 :(得分:9)

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

请改为尝试:

#include <iostream>

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

   return 0;
}

或者:

#include <iostream>

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

   return 0;
}

如果您在0为0时尝试实际输出test,则必须执行以下操作:

#include <iostream>

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

   return 0;
}

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

#include <iostream>

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

   return 0;
}