gpt4 book ai didi

c++ - address-of 运算符是否返回变量引用的值的地址

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:21:15 25 4
gpt4 key购买 nike

我正在阅读 this chapter在指针上,它声明如下:

The address of a variable can be obtained by preceding the name of a variable with an ampersand sign (&), known as address-of operator. For example:

int myvar = 23...;
foo = &myvar;

我的理解是否正确,它是对象 new MyStruct() 的地址,而不是变量本身?我还不太了解变量(不是它们引用的对象)是如何存储的,很可能在编译程序时根本不使用它们。

最佳答案

没有对象23...,那是一个值。有一个名为 myvar 的“对象”,它有一个地址。如果您为变量分配新值,该地址不会改变,它是变量本身的属性。

int var = 23;
int *foo = &var;
var = 35; // foo isn't changed here, it holds the same address.

*foo = 42; // again, foo itself isn't modified

assert(var == 42); // But we modified var through the address in foo

作为旁注,因为您还标记了这个 C++。我只想提一下,由于 C++ 允许您为自己的类重载运算符(其中包括 &),因此整个组合增加了一定的复杂性。但是对于原始变量,使用 & 将始终产生所述变量的地址。

关于c++ - address-of 运算符是否返回变量引用的值的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43247026/

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