引用交换,部分时候代替指针
#include<stdio.h>
void swap(int&a, int&b)
{
int t = a;
a = b;
b = t;
}
int main()
{
int a = 1;
int b = 2;
swap(a,b);
printf("a= %d\tb=%d\n",a ,b);//2, 1
}
引用中的const
让变量拥有只读属性
int a= 1
const int &b = a;
int *p = (int *)&b;
b = 3;//error,b只读
*p = 3;//ok
#include <stdio.h>
void Example()
{
printf("Example:\n");
int a = 4;
const int& b = a;
int* p = (int*)&b;
//b = 5; //b只读
*p = 5;
printf("a = %d\n", a);//5
printf("b = %d\n", b);//5
}
void Demo()
{
printf("Demo:\n");
const int& c = 1;//只读变量分配了4字节空间
int* p = (int*)&c;
//c = 5; //c只读
*p = 5;
printf("c = %d\n", c);//1
}
int main(int argc, char *argv[])
{
Example();
printf("\n");
Demo();
return 0;
}
#include <stdio.h>
struct TRef
{
char& r;
};
int main(int argc, char *argv[])
{
char c = 'c';
char& rc = c;
TRef ref = { c };
printf("sizeof(char&) = %d\n", sizeof(char&));//1
printf("sizeof(rc) = %d\n", sizeof(rc));//1
printf("sizeof(TRef) = %d\n", sizeof(TRef));//8???????????????????
printf("sizeof(ref.r) = %d\n", sizeof(ref.r));//1
return 0;
}
C++用指针实现引用
Type& name: === Type* const name;
void f(int& a)
{
a =5;
}
void f(int* const a)
{
a =5;
}
引用的意义(会变薄角度分析本质是指针的实现)
1.多数情况代替指针
2.避开指针操作不当带来内存错误
3.简单
注意
int& demo()
{
int d = 0;
printf("demo: d = %d\n", d);
return d;
}
不能返回非静态局部变量的引用,值被销毁了。
大总结:
1引用作为变量别名,存在代替指针
2const引用使变量具有只读属性
3引用在编译器内部实现为指针常量的实现,本质为指针
4避免内存出错