Lvalue 參考宣告子: &
保存物件的位址,但語法上的行為與物件相似。
語法
lvalue-reference-type-id
:
type-specifier-seq
&
attribute-specifier-seq
opt opt ptr-abstract-declarator
備註
您可以將左值參考當做物件的另一個名稱。 左值參考宣告包含選擇性的指定名稱清單加上參考宣告符號。 參考必須經過初始化,而且不能變更。
只要物件的位址可以轉換為指定的指標類型,則該物件也可轉換為類似的參考類型。 例如,只要物件的位址可以轉換成 char *
類型,該物件也可轉換成 char &
類型。
請勿混淆參考宣告與使用 位址運算子 。 &
當識別碼 前面加上 類型時,例如 int
或 char
,識別碼 會宣告為型別的參考。 當 &
識別碼 前面沒有類型時,使用方式就是位址運算子的識別碼。
範例
下列範例示範宣告 Person
物件和該物件之參考的參考宣告子。 因為 rFriend
是 myFriend
的參考,無論更新哪一個變數都會變更同一個物件。
// 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
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應