如何获取 C 中通过引用传递的值的值
我有一个具有以下声明的函数:
void cleanValid(int valid[][4], int &size, int index);
在实现该函数时,我需要设置另一个计数器等于通过引用传递的整数大小。我尝试做类似的事情:
int count;
count = size;
如果我没有弄错的话,当我更改 count 的值时,它也会更改 size 的值。但我不能让这种事发生。我将如何将 size 的值复制到 count 中并保持它们独立?
I have a function with the following declaration:
void cleanValid(int valid[][4], int &size, int index);
In implementation of this function I need to set another counter equal to the integer size passed by reference. I tried doing something like:
int count;
count = size;
If I'm not mistaken, when I change the value of count it will change the value of size as well. I can't have this happen though. How would I go about copying the value of size into count and keeping them independent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,你错了。当您从引用读入非引用变量时,您并没有在两者之间建立任何类型的链接。那时你将拥有一个
size
值的独立副本,除此之外别无其他。如果您想要影响
size
的值,则必须使用对其的引用:No, you've got it wrong. When you read from the reference into a non-reference variable, you're not setting up any kind of linkage between the two. You will have an independent copy of the value of
size
at that time, nothing else.If you wanted to affect the value of
size
, you would have to use a reference to it:如果您不想更改
size
,为什么不通过值/const 引用传递呢?或者
在这两个选项中,您都确保
size
不会更改 - 通过让编译器处理它。If you don't want
size
to change, why not pass by value/const reference?or
in both options you ensure
size
is not changed - by letting the compiler take care of it.int count = size
将 size 的值复制到 count 中。如果您在修改副本后更改计数,大小将不受影响。int count = size
copies the value of size into count. If you change count since you are modifying a copy, size will remain unaffected.