1.基本數(shù)據(jù)類型的引用
include<iostream>using namespace stdint main(void){ int a = 10; int &b = a; //是為變量a取了一個別名b b=10; cout<<a<<endl; returen 0;}運行結(jié)果:10。
2.結(jié)構(gòu)體類型的引用
typedef struct{ int x; int y;}Coor;#include<iostream>using namespace std;int main(void){ Coor c; Coor &cr = c; //給結(jié)構(gòu)體變量c取了別名cr cr.x = 1; cr.y = 2; cout<<c.x<<c.y<<endl; return 0;}運行結(jié)果:1 2。
3.指針類型的引用
類型 *&指針引用名 = 指針; // 給指針取別名
#include<iostream>using namespace std;int main(void){ int a = 10; int *p = &a; // 將指針變量p指向變量a的內(nèi)存地址 int *&q = p; // 給指針變量p取個別名q *q = 20; // 將20->*q等價于20->*p,則相當于將20賦予變量。 cout<<a<<endl; return 0;}運行結(jié)果:20。
4.引用作為函數(shù)參數(shù) 舉一個例子,分別使用C語言和C++語言編寫一個函數(shù)。
C語言 void fun(int*a, int*b){ int c = 0; c=*a; *a=*b; *b=c;}int x=10; y = 20;fun(&x,&y);C++語言void fun(int&a, int&b) // 直接將fun調(diào)用的參數(shù)分別取別名為a、b,在函數(shù)書寫中使用引用就可以,函數(shù)更加簡潔。{ int c = 0; c=a; a=b; b=c;}int x =10; y = 20;fun(x,y);新聞熱點
疑難解答
圖片精選