引用的本质
引用的本质是指针常量,指向不能变,但内容可变
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;
引用虽然实质是指针常量,但实际使用过程中有区别,对特定的取址符进行对象替换