引用,编译器的假象

引用的本质

引用的本质是指针常量,指向不能变,但内容可变

int x=0;
int &r=x;
int* const r = &x;

编译器的假象

下面两个是编译器提供的假像,r实际上指针,4个字节

  • sizeof( r ) == sizeof( x )
  • &r==&x
typedef struct tagS
{
	int a, b, c, d;
}S;


void test01()
{
	double x = 0;
	double* p = &x;
	double& r = x;

	cout << sizeof(x) << endl;
	cout << sizeof(p) << endl;
	cout << sizeof(r) << endl;

	cout << p << endl;
	cout << *p << endl;
	cout << x << endl;
	cout << r << endl;
	cout << &x << endl;
	cout << &r << endl;

	cout << endl;
	S s;
	S& rs = s;

	cout << sizeof(s) << endl;
	cout << sizeof(rs) << endl;
	cout << &s << endl;
	cout << &rs << endl;
}

在这里插入图片描述

Reference的特殊使用

struct Reference
{
	int& x;
};

int main()
{
	int a = 1;
	int& b = a;

	int* const p = &a;

	struct Reference c = { a };

	cout << "sizeof(c) = " << sizeof(c) << endl;
	cout << "&a = " << &a << endl;
	cout << "&c = " << &c << endl;
	cout << "&c.x = " << &c.x << endl;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "&a = " << &a << endl;
	cout << "&b = " << &b << endl;
	cout << "p = " << p << endl;
	cout << "&p = " << &p << endl;
	cout << "*p = " << *p << endl;

	b = 2;
	a = 3;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "&a = " << &a << endl;
	cout << "&b = " << &b << endl;

	cout << "p = " << p << endl;
	cout << "&p = " << &p << endl;
	cout << "*p = " << *p << endl;

	system("pause");

	return 0;
}

对引用对象进行取址操作时,返回的并不是引用变量的地址,虽然引用变量自身有地址,但C++做特殊处理返回的是引用对象的值,但是通过特殊方法是能够获取引用变量的地址的
    
int *const p;
引用虽然实质是指针常量,但实际使用过程中有区别,对特定的取址符进行对象替换

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值