c**********e 发帖数: 2007 | 1 大家都知道为什么用reference。但为什么要 const reference?
试了一下,如果用const reference,那么不是 const 的输入也可以。
但如果不用 const reference, 那么 const 的输入 object 就不可以。
但是这个问题的标准答案是什么?还望大牛指点。 |
s*********t 发帖数: 1663 | 2 const表示该函数承诺不会修改该object
const引用不能修改object,所以不能传进非const的函数里
【在 c**********e 的大作中提到】 : 大家都知道为什么用reference。但为什么要 const reference? : 试了一下,如果用const reference,那么不是 const 的输入也可以。 : 但如果不用 const reference, 那么 const 的输入 object 就不可以。 : 但是这个问题的标准答案是什么?还望大牛指点。
|
m*********2 发帖数: 701 | 3 data integrity reason
copy constructor不应该改reference object.
【在 c**********e 的大作中提到】 : 大家都知道为什么用reference。但为什么要 const reference? : 试了一下,如果用const reference,那么不是 const 的输入也可以。 : 但如果不用 const reference, 那么 const 的输入 object 就不可以。 : 但是这个问题的标准答案是什么?还望大牛指点。
|
c**y 发帖数: 172 | 4 By using "const", it indicates that the copy constructor would not change
anything of the parameter being passed.
A non-const reference parameter is automatically cast into a const reference
by the compiler.
However, if the copy constructor is defined with a non-const reference
parameter, then passing a const reference can't go through because the
compiler can't cast the const reference automatically to a non-const
reference. In C++, dynamic_cast is needed to get rid of consistness of the
object.
【在 c**********e 的大作中提到】 : 大家都知道为什么用reference。但为什么要 const reference? : 试了一下,如果用const reference,那么不是 const 的输入也可以。 : 但如果不用 const reference, 那么 const 的输入 object 就不可以。 : 但是这个问题的标准答案是什么?还望大牛指点。
|
m*********2 发帖数: 701 | 5 really?
1) non-const will automatically convert to const when passing?
2) using dynamic_cast<> instead of const_cast<>?
change
reference
the
【在 c**y 的大作中提到】 : By using "const", it indicates that the copy constructor would not change : anything of the parameter being passed. : A non-const reference parameter is automatically cast into a const reference : by the compiler. : However, if the copy constructor is defined with a non-const reference : parameter, then passing a const reference can't go through because the : compiler can't cast the const reference automatically to a non-const : reference. In C++, dynamic_cast is needed to get rid of consistness of the : object.
|
c**y 发帖数: 172 | 6 1) If the parameter is defined as a const, but a non-const is passed, then
the non-const will be cast into a const inside the copy constructor, which
is done by compiler.
2) You're right, it should be const_cast. Thanks for correcting.
【在 m*********2 的大作中提到】 : really? : 1) non-const will automatically convert to const when passing? : 2) using dynamic_cast<> instead of const_cast<>? : : change : reference : the
|
c*******n 发帖数: 63 | 7 使用reference是避免递归调用copy constructor
A a;
A b = a;
如果不用reference,调用copy constructor的时候需要先copy a作为copy
constructor的参数,这就发生无穷递归了 |