# # #, c + + reference
A variable is a “house number” of memory, artificially named so that it can have multiple aliases, which are references.
The main function of ###### reference: as a function parameter or return value, instead of pointer, make the program readable.
-
Simply aliasing a variable is meaningless. Passing it as a function parameter ensures that no copies are generated during parameter passing.
-
A reference can directly manipulate a variable, while a pointer can indirectly manipulate a variable by taking the value (*p). The readability of a pointer is poor.
-
The sizeof the reference is the same as the sizeof the type.
#include
using namespace std;
void main(){
int a = 10; int &b = a; b = 20; cout << b << endl; system("pause"); Copy the code
}
In this example, variable A and reference B essentially access the same memory address. It’s kind of like a pointer.
Examples of value swapping:
#include <iostream> using namespace std; Void swap1(int *a, int *b){int c = *a; *a = *b; *b = c; Void swap2(int &a, int &b){int c = a; a = b; b = c; } void main(){ int a = 10; int b = 20; swap1(&a, &b); swap2(a, b); cout << a << endl; cout << b << endl; // find the largest number, which is b, and then assign b to 30 //C++ tri operator can assign a > b? a : b = 30; cout << b << endl; system("pause"); }Copy the code
#### a reference to a pointer that can replace a secondary pointer
struct Teacher{
char* name;
};
void set1(Teacher** a){
(*a)->name = "wu";
}
void set2(Teacher* &a){
a->name = "lu";
}
void main(){
Teacher t;
Teacher* p_t = &t;
set1(&p_t);
cout << t.name << endl;
set2(p_t);
cout << t.name << endl;
system("pause");
}
Copy the code
#### Pointer constants and constant Pointers
Pointer constants, pointer constants, do not change the address of the pointer, but can change what it points to:
int* const p1 = &a;
//p1 = &b;
*p1 = 30;
Copy the code
Constant pointer: a pointer to a constant that can’t be changed, but can change its address
const int* p2 = &a;
p2 = &b;
//*p2 = 30;
Copy the code
# # # # frequently quoted
-
A reference must have a value, not null, for a pointer. When using Pointers, be careful not to null.
-
Constant reference, cannot be assigned, equivalent to final.
Void set(const int &a){// the reference must have a value. }
void main(){
int x = 0; // reference must have a value, cannot be NULL //int &a = NULL; Final const int a = x; // Final const int a = x; const int &b = 1; System ("pause");Copy the code
}
If you feel that my words are helpful to you, welcome to pay attention to my public number:
My group welcomes everyone to come in and discuss all kinds of technical and non-technical topics. If you are interested, please add my wechat huannan88 and I will take you into our group.