C ++ reference concept
That is a reference map to another variable, or that is an alias for another variable, the variable name with a reference name and variable content can be accessed
definition
int num = 10;
int &r = num; // 创建了引用r
printf("%d\n", num); // 10
printf("%d\n", r); // 10
Unlike pointers
- After the reference must be initialized when they are declared, this is a bit like a constant pointer can be declared no longer be assigned
- Reference can not replace the referenced object, you can only reference a variable from the beginning of creation, and a pointer to an object can be replaced
- Null reference does not exist, it must refer to a valid memory address, and the pointer can be null pointer
Const reference
Typically reference refers only to the same type of values and their
int num = 10;
int &a = num; // 引用a只能引用int型的对象
But by the const
modified reference different, and it can refer to different types of self-reference (the premise is that the system can convert over type), or even a literal reference
int &a = 120; // 错误
const int &a = 120; // 正确