標籤:
#include <iostream>#include <stdlib.h>using namespace std;/*通過此程式可以發現引用的引用變了,原來的值還是會變, *所以定義函數的時候,如果想讓實際變數發生變化,形式 *參數可以定義成引用的形式。另外要注意的是,這裡的&不 *是C中的取地址符號,而是引用的意思。 */ int main(int argc, char** argv){ //定義兩個變數 int x = 100; int y = 200; //為兩個變數建立引用 int &x1 = x; int &y1 = y; //為引用再次建立引用 int &x2 = x1; int &y2 = y1; cout<<"交換變數前:"<<endl; cout<<x<<","<<y<<endl; swap(x,y); cout<<"swap(x,y)"<<endl; cout<<x<<","<<y<<endl; swap(x1,y1); cout<<"swap(x1,y1)"<<endl; cout<<x<<","<<y<<endl; swap(x2,y2); cout<<"swap(x2,y2)"<<endl; cout<<x<<","<<y<<endl; system("pause");}//通過引用來交換兩個變數 void swap(int &x,int &y) { int temp; temp = x; x = y; y = temp;}
#include <stdlib.h>#include <iostream>/*指標的引用為了不被弄暈,可以把int *p寫成int* p,這樣把int*看成一個資料類型, *接下來要建立引用則在int*後面後變數名前面加上&就OK了 */using namespace std;int main(int argc, char** argv){ int x = 100; int* p = &x; int* &q = p; cout<<q<<endl; return 0;}
C++學習記錄(1)——引用