其中&符号“&”表示通过引用传递参数时可以放置吗?

发布于 2025-01-13 20:37:39 字数 198 浏览 5 评论 0原文

在我看到的示例中,参数是按以下方式通过引用传递的:

void AddOne(int &y)

在我拥有的代码中,我看到以下语法:

void AddOne(int& y)

我想知道它是否相同,或者第二种情况与第一种情况是否有某种不同。

In the examples that I saw the arguments were passed by reference in the following way:

void AddOne(int &y)

In the code that I have I see the following syntax:

void AddOne(int& y)

I wonder if it is the same or the second case is somehow different from the first one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

錯遇了你 2025-01-20 20:37:39

两者完全相同。完全没有区别。

重要的是 & 应该位于类型变量名称之间。空格并不重要。

所以

void AddOne(int&  y);
void AddOne(int  &y);
void AddOne(int & y)
void AddOne(int   &     y);
void AddOne(int&y);

都是一样的!

Both are exactly the same. No difference at all.

All that matters is that & should be between the type and the variable name. Spaces don't matter.

So

void AddOne(int&  y);
void AddOne(int  &y);
void AddOne(int & y)
void AddOne(int   &     y);
void AddOne(int&y);

are same!

讽刺将军 2025-01-20 20:37:39

语言是一样的,只是代码约定不同

It's the same for the language, just different code conventions

佼人 2025-01-20 20:37:39

之间没有区别

void AddOne(int &y);

void AddOne(int& y);

,甚至

void AddOne(int&y);

在 C++ 中也没有区别,因为实际标记之间的空格被丢弃。

There is no differences between

void AddOne(int &y);

and

void AddOne(int& y);

and even

void AddOne(int&y);

in C++, as the whitespaces between actual tokens are discarded.

情仇皆在手 2025-01-20 20:37:39

这是风格问题。两者都是正确且有效的。

然而,Bjarne Stroustrup 似乎更喜欢将 &* 放在类型名称旁边,强调变量的类型:

int* i;   // i is a pointer to an int 
int& j;   // j is a reference to an int

请参见此处的指针:https://www.stroustrup.com/bs_faq2.html#whitespace

请参阅“使用 C++ 进行编程原理和实践”一书中的示例以及此处的参考:https://stackoverflow.blog/2019/10 /11/c-creator-bjarne-stroustrup-answers-our-top-5-c-questions/

It is a matter of style. Both are correct and valid.

However it seems Bjarne Stroustrup prefers putting the & and * beside the type name, emphasising the type of the variable:

int* i;   // i is a pointer to an int 
int& j;   // j is a reference to an int

See here for the pointers: https://www.stroustrup.com/bs_faq2.html#whitespace

See examples in "Programming Principles and Practices using C++" book and here for references: https://stackoverflow.blog/2019/10/11/c-creator-bjarne-stroustrup-answers-our-top-five-c-questions/

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