开发者

We say Reference are const pointers. Why I am able to assign a new variable to ref B? The below program compiles successfully

#include<iostream.h>

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

cout<<"B"<<'\n'<<b;
cout<<"A"<<'\n'<<a;
b=100;
cout<<"B"<<'\n'<<b;
cout<<"A"<<'\n'<<a;
int c=开发者_如何学Python20;
b=c;

cout<<"C"<<'\n'<<c;
cout<<"B"<<'\n'<<b;
}


A reference is not a const pointer. A const pointer would need to be dereferenced to access the value. You don't need to dereference references.

A reference is an alias - a new name for the same thing. So the code in your question is valid and a and b refer to the same thing.


I hope you are not getting confused with :

b=c;

This will only assign the value of c to b. It will not refer to c. ( It will still refer to a itself)


Your are not assigning a new variable (referee) to b, but a new value to the variable b refers to, in this case a.


A reference is similar to a const pointer but not to a pointer to const object.

const int* p; //can't change the value of *p
int* const p; //can't change p (make it point to a different int)

References are similar to the latter - once initialized, they can't be made to refer to another object.


Reference is not pointer at all.

int const & b1 = a; // const reference
int       & b2 = a  // non-const reference


when you are doing b = c, you are not referring to c instead you are just assigning value of c to b. If you want verify increment value of c and print both b and c.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜