C++關(guān)于引用作為函數(shù)的用法
介紹
引用是C++中特有的語法,在C語言中不存在。
本質(zhì)上引用(reference)就是指針,在類型名后面加上一個&號就是引用類型。
1.指針與引用的定義進(jìn)行比較
指針定義: 引用定義:
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í)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
wxWidgets實現(xiàn)無標(biāo)題欄窗口拖動效果

