C++

[C++重点]References

2021-01-05  本文已影响0人  greatseniorsde

A compound type is a type that is defined in terms of another type. C++ has several compound types, two of which—references and pointers
A reference defines an alternative name for an object. A reference type “refers to” another type. We define a reference type by writing a declarator of the form &d, where d is the name being declared:

int ival = 1024; 
int &refVal = ival; // refVal refers to (is another name for) ival 
int &refVal2; // error: a reference must be initialized

Ordinarily, when we initialize a variable, the value of the initializer is copied into the object we are creating. When we define a reference, instead of copying the initializer’s value, we bind the reference to its initializer. Once initialized, a reference remains bound to its initial object. There is no way to rebind a reference to refer to a different object. Because there is no way to rebind a reference, references must be initialized.

A reference is not an object. Instead, a reference is just another name for an already existing object.

After a reference has been defined, all operations on that reference are actually operations on the object to which the reference is bound:

refVal = 2; // assigns 2 to the object to which refVal refers, i.e., to ival 
int ii = refVal; // same as ii = ival
上一篇下一篇

猜你喜欢

热点阅读