gpt4 book ai didi

c++ - 通过引用传递与通过指针传递?

转载 作者:IT老高 更新时间:2023-10-28 22:20:47 25 4
gpt4 key购买 nike

Possible Duplicate:
When to pass by reference and when to pass by pointer in C++?

引用传递和指针传递值有什么区别?

最佳答案

当您通过引用传递参数时,函数内部的参数是您从外部传递的变量的别名。当您通过指针传递变量时,您获取变量的地址并将地址传递给函数。主要区别在于您可以将没有地址的值(如数字)传递给采用 const 引用的函数,而不能将无地址的值传递给采用 const 指针的函数。

通常,C++ 编译器将引用实现为隐藏指针。

您可以通过这种方式将函数更改为指针变体:

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 ...
}

关于c++ - 通过引用传递与通过指针传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5893873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com