三元运算符的优先级

在QT2.3.10的源代码中看到如下使用三元运算符的方法,但不知道具体的运算的顺序

    const QCanvasItem* i1 = s1 ?
       (const QCanvasItem*)s1 : p1 ?
       (const QCanvasItem*)p1 : r1 ?
       (const QCanvasItem*)r1 : e1 ?
       (const QCanvasItem*)e1 : (const QCanvasItem*)t1;
    const QCanvasItem* i2 = s2 ?
       (const QCanvasItem*)s2 : p2 ?
       (const QCanvasItem*)p2 : r2 ?
       (const QCanvasItem*)r2 : e2 ?
       (const QCanvasItem*)e2 : (const QCanvasItem*)t2;

 

写了2个小程序分别测试Java和C++的三元运算符的运算顺序  从左到右

 

Java版本

class  test
{
 public static void main(String[] args)
 {
  
  String s1 = null;
  String s2 = null;
  String s3 = "s3";
  String s4 = "s4";

  String s = s1!=null ?printf(s1) : s2!=null ? printf(s2) :  s3!=null ? printf(s3) :  printf(s4);
 }

 static  String printf(String s){
  if(s!=null){
   System.out.println(s);
  }
  return s;
 }
}

程序输出结果:

s3

 

 

C++版本

#include <iostream>
#include <string>

using namespace std;


string* printf(string* s){
 if(s){
  cout << *s << endl;
 }
 return s;
}

int main(int argc,int argv[]){

 string* s1 = 0;
 string* s2 = new string("s2");
 string* s3 = new string("s3");
 string* s4 = new string("s4");

 string* s = s1 ?printf(s1) : s2 ? printf(s2) :  s3 ? printf(s3) :  printf(s4);
 
 if(s){
  cout << "s-->" << *s << endl;
 }
 
}

输出结果:

s2

s-->s2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值