<分区>
我想知道如何让一个函数改变两个变量(返回值和另一个变量),我无意中发现调用函数时在参数前加上一个“&”(我理解是参数的地址)然后在整个过程中你的函数,用'*'符号引用它(我猜这是一个“取消引用”并且意味着它改变了地址处的对象)。
反正一切顺利,然后 friend 说你可以直接用变量调用函数,在header中用&前面引用变量,然后在整个函数中正常对待它。这似乎更容易,那么为什么网络上没有更多关于它的信息呢?一种风格比另一种更正确吗?
void foo(int &junk) //The way the friend said
{
junk++;
}
void oof(int *junk) //what I found, and what the internet seems full of
{
(*junk)++;
}
int main ()
{
int junk=1;
std::cout << junk << "\n";
foo(junk);
std::cout << junk << "\n";
oof(&junk);
std::cout << junk;
}
这个输出:
1
2
3
所以我认为一切正常。