Lvalue 參考宣告子: &

保存物件的位址,但語法上的行為與物件相似。

語法

lvalue-reference-type-id
type-specifier-seq&attribute-specifier-seqopt opt ptr-abstract-declarator

備註

您可以將左值參考當做物件的另一個名稱。 左值參考宣告包含選擇性的指定名稱清單加上參考宣告符號。 參考必須經過初始化,而且不能變更。

只要物件的位址可以轉換為指定的指標類型,則該物件也可轉換為類似的參考類型。 例如,只要物件的位址可以轉換成 char * 類型,該物件也可轉換成 char & 類型。

請勿混淆參考宣告與使用 位址運算子 & 當識別碼 前面加上 類型時,例如 intchar ,識別碼 會宣告為型別的參考。 當 & 識別碼 前面沒有類型時,使用方式就是位址運算子的識別碼。

範例

下列範例示範宣告 Person 物件和該物件之參考的參考宣告子。 因為 rFriendmyFriend 的參考,無論更新哪一個變數都會變更同一個物件。

// 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;
}
Bill is 40

另請參閱

參考
參考型別函式引數
Reference-type 函式會傳回
指標的參考