【C++学习】引用变量
1. 引用变量必须在声明时初始化,且之后无法更改(更改指的是成为其他变量的引用,即:引用变量一旦与某个变量关联起来,就一直效忠于它)
类似于const 指针:
int a = 10; int & re = a; //re的引用不可变 int * const pr = &a; // pr的指向不可变
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int a = 101; 7 int b = 50; 8 int & re = a; 9 cout << "a value: " << a << endl; 10 cout << "a address: " << &a << endl; 11 cout << "b value: " << b << endl; 12 cout << "b address: " << &b << endl; 13 cout << "re value: " << re << endl; 14 cout << "re address: " << &re << endl; 15 re = b; //这里只是将b的值赋值给re引用的变量(a),无法让re引用新的变量(b) 16 cout << "a value: " << a << endl; 17 cout << "a address: " << &a << endl; 18 cout << "b value: " << b << endl; 19 cout << "b address: " << &b << endl; 20 cout << "re value: " << re << endl; 21 cout << "re address: " << &re << endl; 22 return 0; 23 } 24 /* 25 输出 26 a value: 101 27 a address: 0x6dfee8 28 b value: 50 29 b address: 0x6dfee4 30 re value: 101 31 re address: 0x6dfee8 32 a value: 50 33 a address: 0x6dfee8 34 b value: 50 35 b address: 0x6dfee4 36 re value: 50 37 re address: 0x6dfee8 38 */
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int a = 101; 7 int * pt = &a; 8 int & re = *pt; 9 cout << "pt: " << pt << endl; 10 cout << "re: " << &re << endl; 11 cout << "a: " << &a << endl; 12 int b = 50; 13 pt = &b; // pt指向b, 但是re仍然是a的引用 14 cout << "pt: " << pt << endl; 15 cout << "re: " << &re << endl; 16 cout << "a: " << &a << endl; 17 cout << "b:" << &b << endl; 18 return 0; 19 } 20 21 /* 22 输出 23 pt: 0x6dfee4 24 re: 0x6dfee4 25 a: 0x6dfee4 26 pt: 0x6dfee0 27 re: 0x6dfee4 28 a: 0x6dfee4 29 b:0x6dfee0 30 */