gpt4 book ai didi

C++ 参数传递

转载 作者:行者123 更新时间:2023-11-28 05:54:11 25 4
gpt4 key购买 nike

好吧,我刚开始学习 C++,我发现参数传递的来龙去脉有点令人困惑。我在我的 C++ 书中遇到了以下行;

In C++, passing by reference is accomplished in two ways: using pointers and using references.

然后它继续显示一个程序,该程序切换两个 int 值 x 和 y 的值(如下所示)。我想知道,在这种情况下,swap() 函数的参数真的是通过引用传递的吗?我以为它们是按地址传递的,有人告诉我这只是按值传递的特例。

//Listing 9.6 Demonstrates passing by reference 

#include <iostream.h>

void swap(int *x, int *y);

int main()
{
int x = 5, y = 10;

cout << "Main. Before swap, x: " << x
<< " y: " << y << "\n";
swap(&x,&y);
cout << "Main. After swap, x: " << x
<< " y: " << y << "\n";
return 0;
}
void swap(int *px, int *py)
{
int temp;

cout << "Swap. Before swap, *px: "
<< *px << " *py: " << *py << "\n";

temp = *px;
*px = *py;
*py = temp;

cout << "Swap. After swap, *px: " << *px
<< " *py: " << *py << "\n";

}

最佳答案

抽象层次的巧妙融合。

最低级别:当您按值传递 C++ 指针时,指针值被复制。

更高级别:通常指针指向某物,并且该某物在逻辑上通过引用传递。

在 C++ 中通过引用传递最直接的方法是使用引用参数。在幕后,C++ 引用可以(在某些给定情况下)是一个指针,但无法访问或确定有关该指针值的任何内容。所以说引用是按值传递或复制是没有意义的,而是我们谈论绑定(bind)引用或绑定(bind)到引用。

在正确的程序中,引用不能是空引用,这对于作为形式参数类型的引用来说是一个明显的优势。

另一个优点是对 const 的引用可以绑定(bind)到一个临时值,例如

void foo( const std::string& s ) ...

可以这样称呼

foo( "Blah!" )

当使用指针而不是引用来“实现”逻辑引用传递时,这是不可能的。

关于C++ 参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34585474/

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