gpt4 book ai didi

c++ - 按值传递指针和按引用传递指针之间的区别?

转载 作者:行者123 更新时间:2023-12-02 15:17:31 25 4
gpt4 key购买 nike

我目前正在上数据结构和算法类(class),我的教授给我们提供了一些 Material ,其中包括接受指针值指针/引用值的函数。

这些函数看起来像这样:

int function1(int a); // Pass by value
int function2(int &ref); // Pass by reference

int function3(int* ptr); // This will take in a pointer value
int function4(int*& ptr); // This will take in a pointer/reference value

我理解按值传递按引用传递之间的区别。我还尝试将后两个示例实现为基本函数,但我不完全确定这两个参数与按引用传递有何不同,或者它们之间有何不同。

有人可以解释一下这两个函数参数如何工作以及如何实际使用它们吗?

最佳答案

[...] but I am not entirely sure how these two arguments differ from pass by reference or how they differ from each other.

在第一个函数中

int function3(int* ptr);
// ^^^^

您通过指针传递给int。按值表示 int*

在第二个中,

int function4(int*& ptr);
// ^^ --> here

您通过引用指针传递给int。这意味着您正在将引用传递给 int* 类型。

<小时/>

But how does passing the pointer by value and by reference differ in usage from passing a regular variable type such as an integer by value or reference?

同样。当您按值传递指针时,您对传递的指针所做的更改(例如:分配另一个指针)将仅在函数作用域中有效。另一方面,在指针通过引用传递的情况下,您可以直接在main()中更改指针。例如,请参阅以下演示。

#include <iostream>    
// some integer
int valueGlobal{ 200 };

void ptrByValue(int* ptrInt)
{
std::cout << "ptrByValue()\n";
ptrInt = &valueGlobal;
std::cout << "Inside function pointee: " << *ptrInt << "\n";
}

void ptrByRef(int *& ptrInt)
{
std::cout << "ptrByRef()\n";
ptrInt = &valueGlobal;
std::cout << "Inside function pointee: " << *ptrInt << "\n";
}

int main()
{
{
std::cout << "Pointer pass by value\n";
int value{ 1 };
int* ptrInt{ &value };
std::cout << "In main() pointee before function call: " << *ptrInt << "\n";
ptrByValue(ptrInt);
std::cout << "In main() pointee after function call: " << *ptrInt << "\n\n";
}
{
std::cout << "Pointer pass by reference\n";
int value{ 1 };
int* ptrInt{ &value };
std::cout << "In main() pointee before function call: " << *ptrInt << "\n";
ptrByRef(ptrInt);
std::cout << "In main() pointee after function call: " << *ptrInt << "\n\n";
}
}

输出:

Pointer pass by value
In main() pointee before function call: 1
ptrByValue()
Inside function pointee: 200
In main() pointee after function call: 1

Pointer pass by reference
In main() pointee before function call: 1
ptrByRef()
Inside function pointee: 200
In main() pointee after function call: 200

关于c++ - 按值传递指针和按引用传递指针之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59386536/

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