關(guān)于&和*運(yùn)算符的疑惑
老師好!為什么*可以這么用:
int?const?*myAge?=?&age; int?*?const?myAge?=?&age; const?int?*?const?pi2?=?&age; int?const?*?const?pi2?=?&age;
而&不可以這么用,但是如果這么用:
int?const?&myAge?=?age; int?&?const?myAge?=?age; const?int?const?&myAge?=?age; const?int?&?const?myAge?=?age;
vs2013下會報錯但可以運(yùn)行,&和*到底有什么本質(zhì)上的差別(老師的課講的真好)
#include?<iostream> using?namespace?std; int?main(){ int?age?=?22; int?yourAge?=?23; const?int?&myAge?=?age;?//age的別名myAge是量量,也就是說不能通過myAge重新給age賦值 const?int?*pi?=?&age;//*pi是常量指針,不能通過*pi重新給age賦值 int?*?const?pi1?=?&age;//pi1是常量,pi1所存儲的地址不能修改 //下面兩行代碼等價 const?int?*?const?pi2?=?&age; int?const?*?const?pi2?=?&age; cout?<<?myAge?<<?endl; cout?<<?&myAge?<<?endl; /*int?const?&myAge?=?age; cout?<<?myAge?<<?endl; cout?<<?&myAge?<<?endl;*/ /*int?&?const?myAge?=?age; cout?<<?myAge?<<?endl; cout?<<?&myAge?<<?endl;*/ /*const?int?const?&myAge?=?age; cout?<<?myAge?<<?endl; cout?<<?&myAge?<<?endl;*/ /*const?int?&?const?myAge?=?age; cout?<<?myAge?<<?endl; cout?<<?&myAge?<<?endl;*/ return?0; }
2015-10-18
在聲明(定義)時,前面加&代表所聲明的變量是引用類型,前面的*代表指針類型。
第一段代碼中,為指針賦值時,等號右側(cè)忘了寫&。
第二段代碼中,聲明引用時不能在&后面加上cosnt。 引用原本就是const的。
第三段代碼中:
第9行, myAge為const引用,引用的是age變量。沒問題。
第11行, pi為指向const int的指針,指向age變量。 沒問題。
第12行, pi1為指向int的const指針,指向age變量。 沒問題。
第14行, pi2為指向const int的const指針,指向age變量。 沒問題。
第15行,其實(shí)這樣和14行是一樣的,單看這語句也沒問題,但你重復(fù)定義了pi2。這句會報錯的,且無法編譯通過。
2015-10-18
引用原本就是const的