gpt4 book ai didi

c++ - 通过引用和指针传递参数 C++

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

我正在查看一个代码片段并且我有这个序列。

class MyVariable {
....
CustomType z;
....
}

A.cpp

调用函数 f ( & myVariable)

在包含的文件中我确实有这个:

B.h

void f ( MyVariable * myVariable);

B.cpp

f( MyVariable * myVariable){
CustomType & x = myVariable ->g();
}

其中 g 是 MyVariable 类的一个方法,实现是:

CustomType & g() {
...
return z; //where you can find z in the class
}

虽然对我来说它看起来很复杂,所以我的问题是:

对 x 的任何更改是否反射(reflect)到用作 A.cpp 函数调用中的参数的 myVariable?

换句话说,如果在 B.cpp 中,我会做这样的事情:

// change x with some value

该更改是否也会反射(reflect)在 myVariable 中?

最佳答案

是的。任何地方都没有拷贝,因为当您将变量从一个地方“传递”到另一个地方时,您使用的是指针或引用,所以您实际上在所有地方都使用了相同的变量。

g() 中,你返回一个 referencez,然后在 f() 中你保持此对 z 的引用。此外,当您调用 f() 时,您甚至不会复制 myVariable,而是复制它的地址(以指针的形式),因此您实际上会修改您在 A.cpp 中拥有的 myVariable 变量的 z 成员。

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

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