因為很重要,所以我打了3次。
言歸正傳:
下面這個範例完整了呈現指標和參考,多多去試著亂輸入一通,
才能夠真正了解怎麼將記憶體位址指向誰,或是說哪個值去參考誰?
//
#include <iostream> #include <cstdlib> using namespace std; int main(){ cout<<"---Pointer---"<<endl; int a; int *pa; a =10; pa = &a; //pa去取a的值 cout<<a<<", "<<*pa<<endl; a++; cout<<a<<", "<<*pa<<endl; (*pa)++; cout<<a<<", "<<*pa<<endl; //Reference: 需在宣告的時候,指定參考對象,事後不可轉向靜態! //只有在宣告的時候加上& cout<<"---Reference---"<<endl; int b; //&rb參考到b的記憶體位置 int &rb =b; b=20; cout<<b<<", "<<rb<<endl; b++; cout<<b<<", "<<rb<<endl; rb++; cout<<b<<", "<<rb<<endl; cout<<"---Test---"<<endl; cout<<"&a:"<<&a<<endl; cout<<"pa:"<<pa<<endl; cout<<"&pa:"<<&pa<<endl; cout<<"&b:"<<&b<<endl; cout<<"&rb:"<<&rb<<endl; return 0; }
執行結果:
沒有留言:
張貼留言