条件表达式? : 的值问题

条件表达是(B?A :C),由于其运算结果运行时才能得到,故在编译阶段,有一个类型提升过程, 该表达式的值为A和C中较高的类型。看下面的代码:
#include <iostream>
#include <typeinfo.h>

using namespace std;

int main()
{
    cout<<typeid(true?1.0:1).name()<<endl;
   cout<<typeid(true?1:1.0).name()<<endl;
    return 0;
}

输出:
double
double

所以有引申出一个问题: 条件表达式 在何种状况下不能修改为"if (..) {..} else {..}"?
看这段代码:
#include <iostream>

using namespace std;

void f(double)
{
cout
<< "double" << endl;
}

void f(int)
{
cout
<< "int" << endl;
}

int main()
{
f(
true ? 1 : 1.0); //调用f(double)函数,因为重载解析编译阶段进行,条件表达式产生类型提升
if(true)
{
f(
1);
}
else
{
f(
1.0);
}
}

输出为:
double
int
讨论帖:http://topic.csdn.net/u/20071021/12/d5c77a04-38cc-4f8a-b322-8e6c83354921.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值