通过引用传递参数时,与号 "&" 可以放在哪里?

Where ampersand "&" can be put when passing argument by reference?

本文关键字:在哪里 与号 引用 参数      更新时间:2023-10-16

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

void AddOne(int &y)

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

void AddOne(int& y)

我想知道它是相同的还是第二个案例与第一个不同。

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

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

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

是相同的!

对于语言来说是一样的,只是代码约定不同

void AddOne(int &y);

void AddOne(int& y);

void AddOne(int&y);

,因为实际标记之间的空白被丢弃。

这是一个风格问题。都是正确有效的

然而,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-five-c-questions/