引用的本质就是指针,只是编译器削弱了它的功能,所以引用就是弱化了的指针
一个引用占一个指针的大小
#include<iostream>
using namespace std;
int main() {
int age = 10;
int height = 20;
int &ref = age;
ref = 20;
cout << age << endl;
ref += 30;
cout << age << endl;
ref = height;
ref = 11;
cout << height << endl;
int &ref = age;
int &ref1 = ref;
int &ref2 = ref1;
getchar();
return 0;
}
#include<iostream>
using namespace std;
void test() {
int age = 10;
int height = 20;
int &ref = age;
int &ref1 = ref;
int &ref2 = ref1;
ref += 10;
ref1 += 10;
ref2 += 10;
cout << age << endl;
}
void swap(int &v1, int &v2) {
int tmp = v1;
v1 = v2;
v2 = tmp;
}
int main(){
int a = 10;
int b = 20;
swap(a, b);
cout << "a=" << a << ",b=" << b << endl;
getchar();
return 0;
}
#include<iostream>
using namespace std;
struct Date{
int year;
int month;
int day;
};
int main(){
Date d = { 2021, 9, 17 };
Date &ref1 = d;
ref1.year = 2022;
int age = 10;
int *p = &age;
int *&ref2 = p;
*ref2 = 30;
int height = 30;
ref2 = &height;
int array[] = { 1, 2, 3 };
int(&ref3)[3] = array;
int * const &ref3 = array;
int *arr1[3];
int(*arr2)[3];
int age = 10;
int &ref = age;
getchar();
return 0;
}