Contents
•
Reference
•
Template
2
Declaring references
•
References are a new data type in C++
– char c; // a character
– char* p = &c; // a pointer to a character
– char& r = c; // a reference to a character
•
Local or global variables
–
type& refname = name;
–
For ordinary variables, the initial value is required
•
In parameter lists and member variables
–type& refname
–
Binding defined by caller or constructor
3
References
•
Declares a new name for an existing object
int X = 47;
int& Y = X;! // Y is a reference to X
// X and Y now refer to the same variable
cout << "Y = " << Y; // prints Y = 47
Y = 18;
cout << "X = " << X; // prints X = 18
4
Rules of references
•
References must be initialized when defined
•
Initialization establishes a binding
•
In declaration
int x = 3;
int& y = x;
const int& z = x;
•
As a function argument
void f ( int& x );
f(y); // initialized when function is called
5
评论0