常量引用 - C++
我对 C++ 中 const 引用的概念有疑问。
int i =10;
const int &j = i;
cout<<"i="<<i<<" j:"<<j; // prints i:10 j:10
i = 20;
cout<<"i="<<i<<" j:"<<j; // prints i:20 j:10
为什么第二个j
语句不打印新值,即20
。
如果对任何变量的引用都表示它们之间有很强的联系,那怎么可能呢?
I had a doubt regarding the concept of const references in C++.
int i =10;
const int &j = i;
cout<<"i="<<i<<" j:"<<j; // prints i:10 j:10
i = 20;
cout<<"i="<<i<<" j:"<<j; // prints i:20 j:10
Why second j
statement doesn't print the new value i.e 20
.
How it is possible if references to any variable denotes strong bonding between both of them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个编译器错误。该代码应打印
20 20
。That is a compiler bug. The code should print
20 20
.我不明白为什么
j
不会在第二个cout
中打印20
。我运行了这段代码:
它给了我这个输出:
自己查看在线演示:http://ideone.com/ELbNa
这意味着,要么您正在使用的编译器有错误(这种情况不太可能发生,因为它是 C++ 中最基本的东西),要么您没有正确看到输出(最有可能是这种情况) 。
I don't see any reason why
j
wouldn't print20
in the secondcout
.I ran this code :
And it gave me this output:
See the online demo yourself : http://ideone.com/ELbNa
That means, either the compiler you're working with has bug (which is less likely the case, for its the most basic thing in C++), or you've not seen the output correctly (which is most likely the case).
const引用意味着它不能改变引用对象的值。但是,引用可以更改其值,从而影响引用。我不知道你为什么会得到你所显示的输出。
它实际上发生了变化,请在此处查看输出。
const reference means it cannot change the value of the refferant. However, referrant can change it's value which in turn affects the reference. I don't know why you are getting the output you shown.
It actually changes and see the output here.
这里还要补充一点,
const
引用不需要左值来初始化它。例如Just to add one more point here,
const
reference doesn't require lvalue to initialize it. For example