如何获取 C 中通过引用传递的值的值

发布于 2024-08-10 09:45:24 字数 300 浏览 7 评论 0原文

我有一个具有以下声明的函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

○愚か者の日 2024-08-17 09:45:24

不,你错了。当您从引用读入非引用变量时,您并没有在两者之间建立任何类型的链接。那时你将拥有一个 size 值的独立副本,除此之外别无其他。

如果您想要影响size的值,则必须使用对其的引用:

int& count = size;

/* ... */    
count= 32;  /* This will change size, too. */

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:

int& count = size;

/* ... */    
count= 32;  /* This will change size, too. */
眼趣 2024-08-17 09:45:24

如果您不想更改 size,为什么不通过值/const 引用传递呢?

void cleanValid(int valid[][4], int size, int index);

或者

void cleanValid(int valid[][4], const int &size, int index);

在这两个选项中,您都确保 size 不会更改 - 通过让编译器处理它。

If you don't want size to change, why not pass by value/const reference?

void cleanValid(int valid[][4], int size, int index);

or

void cleanValid(int valid[][4], const int &size, int index);

in both options you ensure size is not changed - by letting the compiler take care of it.

生来就爱笑 2024-08-17 09:45:24

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文