?:操作符是一個條件賦值的操作符號,常用來對變量進行條件賦值如:
int i = 1, j = 2;
int c_max = ( i > j ? i : j );
不過今天看了網上的一段代碼,是這樣用的
(i->second.left ? file.leechers : file.seeders)--;
上面的三個都是變量,也可以編譯通過,所以寫了段代碼試了一下
?1?void?show_1(int?val)
?2?{
?3?????cout?<<?"function?show_1?called!"?<<?endl;
?4?}
?5?
?6?
?7?void?show_2(int?val)
?8?{
?9?????cout?<<?"function?show_2?called!"?<<?endl;
10?}
11?
12?
13?void?quest_test()
14?{
15?????int?c?=?0;
16?????int?a?=?1,?b?=?2;
17?????(c++???a?:?b)--;
18?????cout?<<?a??<<?"?and?"??<<?b?<<?endl;
19?????(c???a?:?b)++;
20?????cout?<<?a??<<?"?and?"??<<?b?<<?endl;
21?????(c???show_1?:?show_2)(100);
22?}
23?
24?
25?最后的輸出是
26?1?and?1
27?2?and?1
28?function?show_1?called!
最怪的是?:操作符號,居然也可以用在函數上.
(c ? show_1 : show_2)(100);
其實等同于
if (c)
? show_1(100);
else
? show_2(100);
不過簡練了很多.