介紹
引用是C++中特有的語法,在C語言中不存在。
本質上引用(reference)就是指針,在類型名后面加上一個&號就是引用類型。
1.指針與引用的定義進行比較
指針定義: 引用定義:
int a = 123; int a =123;
int* p = &a; int& r = a;
稱作:p指向了變量a 稱作:r是變量a的引用或r引用了目標對象a
2.引用可以看作是目標對象的一個別名,對引用的操作其實都是對目標對象的操作。
3.引用必須在定義時初始化,也就是一創建就要與目標對象綁定。
int a = 124; int &r; //語法錯,必須初始化
引用作為函數參數
#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;}
引用作為函數的返回值
#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;}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答