C++ 引用
作者:互联网
10. 引用
- References are a new data type in C++;
- Local or global variables
- For ordinary variables, the initial value is required
- In parameter lists and member variables
- Binding defined by caller or constructor
char c; // a character
char* p = &c; // a pointer to a character
char& r = c; // a reference to a character
10.1 引用详解
- 引用就是别名
- 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 << endl;
Y = 18;
cout << "X = " << X << endl;
10.2 引用的规则
- 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
10.3 示例
#include <iostream>
using namespace std;
int* f(int* x) {
(*x)++;
return x;
}
int& g(int& x) {
x++;
return x;
}
int x;
int& h() {
int q;
return x;
}
int main() {
int a = 0;
f(&a); // Ugly (but explicit)
cout << "f(&a) = " << a << endl;
g(a); // Clean (but hidden)
cout << "g(a) = " << a << endl;
h() = 16;
cout << "h() = " << x << endl;
}
10.4 Pointers vs. References
-
Pointers
- can be set to null
- pointer is independent of existing objects
- can change to point to a different address
-
References
- can't be null
- are dependent on an existing variable, they are an alias for an variable
- can't change to a new "address" location
-
约束
// No references to references
// No pointers to references
int&* p; // illegal
// Reference to pointer is ok
void f(int*& p); // ok
// No arrays of references
参考链接:
标签:No,int,C++,existing,References,引用,references,pointer 来源: https://www.cnblogs.com/linkworld/p/16380775.html