Lvalue 参照宣言子: &

オブジェクトのアドレスを保持しますが、オブジェクトのように構文的に実行されます。

構文

lvalue-reference-type-id:
type-specifier-seq&attribute-specifier-seqoptptr-abstract-declaratoropt

解説

lvalue 参照は、オブジェクトの別名と考えることができます。 左辺値参照の宣言は、参照宣言子が続く指定子のオプションのリストから構成されます。 参照は初期化する必要があり、変更できません。

アドレスを特定のポインター型に変換できるオブジェクトは、類似した参照型にも変換できます。 たとえば、アドレスを 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

関連項目

参照
参照型関数の引数
参照型関数が返す
ポインターへの参照