Redian新闻
>
C++: define a reference always reference the same object
avatar
C++: define a reference always reference the same object# Programming - 葵花宝典
i*p
1
How can I define a reference to ensure it will always reference the same
object but you can use the reference to modify the object's values?
The follow FAQ says a reference is always const. Do you agree it?
http://www.parashift.com/c++-faq-lite/const-correctness.html
...
[18.7] Does "Fred& const x" make any sense?
No, it is nonsense.
To find out what the above declaration means, you have to read it right-to-
left. Thus "Fred& const x" means "x is a const reference to a Fred". But
that is redunda
avatar
i*p
2
I can reseat a reference by the following code and g++ does not generate any
error.
base& ref_1 = b;
ref_1 = c;

【在 i**p 的大作中提到】
: How can I define a reference to ensure it will always reference the same
: object but you can use the reference to modify the object's values?
: The follow FAQ says a reference is always const. Do you agree it?
: http://www.parashift.com/c++-faq-lite/const-correctness.html
: ...
: [18.7] Does "Fred& const x" make any sense?
: No, it is nonsense.
: To find out what the above declaration means, you have to read it right-to-
: left. Thus "Fred& const x" means "x is a const reference to a Fred". But
: that is redunda

avatar
c*g
3
it's not a reseat, but an assignment.
you can check what happens to b after you "reseating" ref_1 by c.

any

【在 i**p 的大作中提到】
: I can reseat a reference by the following code and g++ does not generate any
: error.
: base& ref_1 = b;
: ref_1 = c;

avatar
i*p
4
You are right. b.i is 'C'. This is an assignment to b by reference ref_1.

【在 c*****g 的大作中提到】
: it's not a reseat, but an assignment.
: you can check what happens to b after you "reseating" ref_1 by c.
:
: any

avatar
i*p
5
Now let us back to my original question.
How can I define a reference to ensure it will always reference the same
object but you can use the reference to modify the object's values?
So according to our analysis, we don't need to do anything special but just
declare a simple reference like this,
base& ref_1 = b;
Am I right?

【在 i**p 的大作中提到】
: You are right. b.i is 'C'. This is an assignment to b by reference ref_1.
avatar
f*y
6
i think you are right. That is the definition of reference.

just

【在 i**p 的大作中提到】
: Now let us back to my original question.
: How can I define a reference to ensure it will always reference the same
: object but you can use the reference to modify the object's values?
: So according to our analysis, we don't need to do anything special but just
: declare a simple reference like this,
: base& ref_1 = b;
: Am I right?

avatar
W*g
7
reference不能被重新赋值你不知道么?
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。