标签:分享 功能性 细节 before 技术分享 ++ name bsp 存储空间
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
void swap_yinyong(int& a,int& b)
{
int t = a;
a = b;
b = t;
}
int main()
{
int a = 1;
int b = 2;
printf("a = %d,b = %d\n",a,b);
swap(&a,&b);
printf("指针版本:a = %d, b = %d\n",a,b);
swap_yinyong(a,b);
printf("引用版本:a = %d, b = %d\n",a,b);
return 0;
}
Const Type& name = val;
Const 引用让变量拥有只读属性
int main()
{
int a = 1;
const int& b = a;
int *p = (int*)&b;
//b = 5; 编译报错,显示不能对只读变量赋值
*p = 5; //要想改变只读变量,可以对他的指针进行操作
printf("a = %d\n",a);
return 0;
}
int main()
{
const int& b = 1;
int *p = (int*)&b;
*p = 5; //要想改变只读变量,可以对他的指针进行操作
printf("a = %d\n",b);
return 0;
}
使用常量对const引用初始化后将生成一个只读变量
struct Tref
{
char& c;
};
int main()
{
char c = ‘c‘;
char& rc = c;
Tref ref = { c };
printf("sizeof(char&)%d\n",sizeof(char&));
printf("sizeof(rc)%d\n",sizeof(rc));
printf("sizeof(ref.c)%d\n",sizeof(ref.c));
printf("sizeof(Tref)%d\n",sizeof(Tref));
return 0;
}
struct Tref
{
char* before;
char& ref;
char* after;
};
int main()
{
char a = ‘a‘;
char b = ‘b‘;
char c = ‘c‘;
Tref r = {&a,b,&c};
printf("sizeof(r)%d\n",sizeof(r));
printf("sizeof(Tref.before)%d\n",sizeof(r.before));
printf("sizeof(Tref.after)%d\n",sizeof(r.after));
printf("&r.before=%p\n",&r.before);
printf("&r.after= %p\n",&r.after);
return 0;
}
标签:分享 功能性 细节 before 技术分享 ++ name bsp 存储空间
原文地址:https://www.cnblogs.com/ryluo/p/10037288.html