gpt4 book ai didi

c++ - 什么是常数引用? (不是对常量的引用)

转载 作者:IT老高 更新时间:2023-10-28 13:22:54 26 4
gpt4 key购买 nike

为什么常量引用的行为方式与常量指针不同,以便我可以实际更改它们指向的对象?它们真的看起来像是另一个简单的变量声明。为什么我会使用它们?

这是我运行的一个简短示例,它编译并运行没有错误:

int main (){
int i=0;
int y=1;
int&const icr=i;
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99; // Can assign another value but the value is not assigned to y...
int x=9;
icr=x;
cout<<"icr: "<<icr<<", y:"<<y<<endl;
}

最佳答案

最清楚的答案。 Does “X& const x” make any sense?

No, it is nonsense

To find out what the above declaration means, read it right-to-left:“x is a const reference to a X”. But that is redundant — referencesare always const, in the sense that you can never reseat a referenceto make it refer to a different object. Never. With or without theconst.

In other words, “X& const x” is functionally equivalent to “X& x”.Since you’re gaining nothing by adding the const after the &, youshouldn’t add it: it will confuse people — the const will make somepeople think that the X is const, as if you had said “const X& x”.

关于c++ - 什么是常数引用? (不是对常量的引用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7420780/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com