定义
与指针相似的是,引用将存储位于内存中其他位置的对象的地址。 与指针不同的是,初始化之后的引用无法引用不同的对象或设置为 null。
声明方式
# 引用、指针和对象可以一起声明
int &ref, *ptr, k;
引用保留对象的地址,但语法行为与对象一样。
// references.cpp
#include <stdio.h>
struct S {short i;
};int main() {S s; // Declare the object.S& SRef = s; // Declare and initialize the reference.s.i = 3;printf_s("%d\n", s.i);printf_s("%d\n", SRef.i);SRef.i = 4;printf_s("%d\n", s.i);printf_s("%d\n", SRef.i);
}
引用与被引用的变量指向同一地址因此,改变任意变量,会引起整体变量的改变
// reference_declarator.cpp
// compile with: /EHsc
// Demonstrates the reference declarator.
#include <iostream>
using namespace std;struct Person
{char* Name;short Age;
};int main()
{// Declare a Person object.Person myFriend;// Declare a reference to the Person object.Person& rFriend = myFriend;// Set the fields of the Person object.// Updating either variable changes the same object.myFriend.Name = "Bill";rFriend.Age = 40;// Print the fields of the Person object to the console.cout << rFriend.Name << " is " << myFriend.Age << endl;
}
# output:Bill is 40
函数参数传递引用,这使编译器能够在保持已用于访问对象的语法的同时传递对象的地址。
// reference_type_function_arguments.cpp
#include <iostream>
#结构体Date
struct Date
{short Month;short Day;short Year;
};// Create a date of the form DDDYYYY (day of year, year)
// from a Date.
long DateOfYear( Date& date )
{
// 静态整型数组static int cDaysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};long dateOfYear = 0;// Add in days for months already elapsed.for ( int i = 0; i < date.Month - 1; ++i )dateOfYear += cDaysInMonth[i];// Add in days for this month.dateOfYear += date.Day;// Check for leap year.if ( date.Month > 2 &&(( date.Year % 100 != 0 || date.Year % 400 == 0 ) &&date.Year % 4 == 0 ))dateOfYear++;// Add in year.dateOfYear *= 10000;dateOfYear += date.Year;return dateOfYear;
}int main()
{Date date{ 8, 27, 2018 };long dateOfYear = DateOfYear(date);std::cout << dateOfYear << std::endl;
}
对指针的引用
声明对指针的引用的方式与声明对对象的引用差不多。 对指针的引用是一个可像常规指针一样使用的可修改的值。
// https://learn.microsoft.com/zh-cn/cpp/cpp/references-to-pointers?view=msvc-170