介紹
引用是C++中特有的語法,在C語言中不存在。
本質(zhì)上引用(reference)就是指針,在類型名后面加上一個&號就是引用類型。
1.指針與引用的定義進行比較
指針定義: 引用定義:
int a = 123; int a =123;
int* p = &a; int& r = a;
稱作:p指向了變量a 稱作:r是變量a的引用或r引用了目標(biāo)對象a
2.引用可以看作是目標(biāo)對象的一個別名,對引用的操作其實都是對目標(biāo)對象的操作。
3.引用必須在定義時初始化,也就是一創(chuàng)建就要與目標(biāo)對象綁定。
int a = 124; int &r; //語法錯,必須初始化
引用作為函數(shù)參數(shù)
#include <stdio.h>int add(int& a, int& b){ return a + b; }int main(){ int a = 1, b = 2; printf("%d/n", add(a, b)); return 1;}引用作為函數(shù)的返回值
#include <stdio.h>#include <string.h>struct Student{ char name[32]; int age;};Student stu;Student& fun(){ strcpy(stu.name, "aaa"); stu.age = 30; return stu;}int main(){ Student& stu = fun(); printf("name = %s, age = %d/n", stu.name, stu.age); return 1;}總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點
疑難解答