且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

c++ 函数:将非 const 参数传递给 const 引用参数

更新时间:2023-11-11 17:26:34

引用是常量,不是对象.它不会改变对象是可变的这一事实,但是您有一个可以修改它的对象名称 (j) 和另一个名称 (i) 你不能通过它.

The reference is const, not the object. It doesn't change the fact that the object is mutable, but you have one name for the object (j) through which you can modify it, and another name (i) through which you can't.

在 const 引用参数的情况下,这意味着 main 可以修改对象(因为它使用它的名称 j),而 func 不能修改对象,只要它只使用它的名称 i.func 可以 原则上通过使用 const_cast 创建另一个引用或指向它的指针来修改对象,但不要这样做.

In the case of the const reference parameter, this means that main can modify the object (since it uses its name for it, j), whereas func can't modify the object so long as it only uses its name for it, i. func could in principle modify the object by creating yet another reference or pointer to it with a const_cast, but don't.