通过引用与通过指针传递? [英] Pass by reference vs pass by pointer?
问题描述
可能重复:
何时通过引用和何时在C ++中通过指针传递?
通过引用传递和通过指针传递值之间有什么区别?
What is the difference between passing by reference and passing the value by a pointer?
推荐答案
通过引用传递参数时,函数内部的参数是您从外部传递的变量的别名.当您通过指针传递变量时,您将获取变量的地址并将该地址传递给函数.主要区别在于,您可以将不带地址的值(如数字)传递给采用const引用的函数,而不能将不带地址的值传递给采用const指针的函数.
When you pass a parameter by reference, the parameter inside the function is an alias to the variable you passed from the outside. When you pass a variable by a pointer, you take the address of the variable and pass the address into the function. The main difference is that you can pass values without an address (like a number) into a function which takes a const reference, while you can't pass address-less values into a function which takes const pointers.
通常,C ++编译器将引用实现为隐藏指针.
Typically a C++ compiler implement a reference as a hidden pointer.
您可以通过以下方式将函数更改为指针变量:
You can change your function into the pointer variant this way:
void flip(int *i) // change the parameter to a pointer type
{
cout << " flip start "<<"i="<< *i<<"\n"; // replace i by *i
*i = 2*(*i); // I'm not sure it the parenthesis is really needed here,
// but IMHO this is better readable
cout << " flip exit "<<"i="<< *i<<"\n";
}
int main()
{
int j =1;
cout <<"main j="<<j<<endl;
flip(&j); // take the address of j and pass this value
// adjust all other references ...
}
这篇关于通过引用与通过指针传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!