[心得] *&傻傻分不清楚
大家來複習一下point及reference吧!
大師級的各位也可以當成是一種娛樂(誤),
試解釋下列定義:
int a;
int ary[10]={0,1,2,3,4,5,6,7,8,9};
int *p = &a; //...(1)
int &r = a; //...(2)
int *pp = ary; //...(3)
int &rr = *ary; //...(4)
int (*ppp)[10] = &ary; //...(5)
int (&rrr)[10] = ary; //...(6)
Ans:
(1)(2) -> point to variable, reference to variable
(3)(4) -> point to array, reference to array element.
(5)(6) -> point to array, reference to array. (given size)
其中稍微有趣的就是(3)和(6)的比較,
同樣都是對ary做賦值的動作,
但如果Compiler發現宣告的是一個reference to array,
便不會把ary轉為point to array,取而代之的是reference to array,
因此這個例子中就可以這樣使用:
for(int i=0; i<10; i++)
cout << rrr[i];
cout << endl;
//output 0123456789
以上,純屬分享 ^_^
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.218.105.109
→
04/14 12:19, , 1F
04/14 12:19, 1F
推
04/15 00:27, , 2F
04/15 00:27, 2F
→
04/15 09:02, , 3F
04/15 09:02, 3F