【发布时间】:2012-03-28 13:12:43
【问题描述】:
为什么在条件运算符(?:)中,第二个和第三个操作数的类型必须相同?
我的代码是这样的:
#include <iostream>
using std::cout;
int main()
{
int a=2, b=3;
cout << ( a>b ? "a is greater\n" : b ); /* expression ONE */
a>b? "a is greater\n" : b; /* expression TWO */
return 0;
}
使用g++编译时报错:
main.cpp:7:36: error: operands to ?: have different types ‘const char*’ and ‘int’
main.cpp:8:28: error: operands to ?: have different types ‘const char*’ and ‘int’
我想知道为什么它们必须具有相同的类型?
(1) 在我看来,如果(a>b) 为真,那么表达式( a>b ? "a is greater\n" : b ) 将返回"a is greater\n" 和cout << "a is greater\n" 将输出该字符串;
否则表达式将返回b,cout << b 将输出b的值。
但是,不幸的是,它不是这样的。为什么?
(2) 第二个表达式得到同样的错误。
PS:我知道,是标准说一定要这样,但是,为什么标准这么说呢?
【问题讨论】:
-
请注意,它们不一定必须具有完全相同的类型;可以进行一些转化,但允许的转化次数很少,以避免意外行为。
标签: c++ c operator-keyword