左值引用声明符: &Lvalue Reference Declarator: &

保留对象的地址,但行为方式在语法上与对象相似。Holds the address of an object but behaves syntactically like an object.

语法Syntax

type-id & cast-expression

备注Remarks

您可以将左值引用视为对象的另一名称。You can think of an lvalue reference as another name for an object. 左值引用声明由说明符的可选列表后跟一个引用声明符组成。An lvalue reference declaration consists of an optional list of specifiers followed by a reference declarator. 引用必须初始化且无法更改。A reference must be initialized and cannot be changed.

地址可转换为给定指针类型的任何对象也可转换为相似的引用类型。Any object whose address can be converted to a given pointer type can also be converted to the similar reference type. 例如,地址可转换为类型 char * 的任何对象也可转换为类型 char &For example, any object whose address can be converted to type char * can also be converted to type char &.

请不要将引用声明与使用混淆address-of 运算符Do not confuse reference declarations with use of the address-of operator. &标识符前面都有一个类型,如intchar标识符声明为对的引用类型。When the &identifier is preceded by a type, such as int or char, identifier is declared as a reference to the type. &标识符前面没有类型,用法就是 address-of 运算符的。When &identifier is not preceded by a type, the usage is that of the address-of operator.

示例Example

以下示例通过声明 Person 对象和对该对象的引用演示了引用声明符。The following example demonstrates the reference declarator by declaring a Person object and a reference to that object. 由于 rFriend 是对 myFriend 的引用,因此更新任一变量都将更改同一对象。Because rFriend is a reference to myFriend, updating either variable changes the same object.

// 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

请参阅See also

参考资料References
引用类型函数自变量Reference-Type Function Arguments
引用类型函数返回Reference-Type Function Returns
对指针的引用References to Pointers