gpt4 book ai didi

c++ - 左值和右值与 C++ 数组

转载 作者:行者123 更新时间:2023-12-03 06:54:31 29 4
gpt4 key购买 nike

我对数组做了一些实验并学习了 L 值和 R 值,
根据我的理解:

L-values are object that has an identifiable memory location, R-values are defined by exclusion, anything that is not a L-value, is a R-value, by exclusion.


这是我的实验:
int array [] = {8, 7, 6, 5, 4};            
std::cout << array << std::endl; //0x61fedc
std::cout << &array << std::endl; //0x61fedc
std::cout << *(&array) << std::endl; //0x61fedc
std::cout << *array << std::endl; //8
第 1 行和第 2 行应该毫无意外,当您评估数组时,它将返回第一个元素的地址
令人困惑的是第 3 行的结果。 *(&array)对我说“变量 array 的第一个内存地址的取消引用值是多少,我期待 8 ,但是我找回了第一个内存地址,这是为什么?
最后,第 4 行计算结果为 8 ,这是预料之中的。但是,由于取消引用运算符适用于 array变量,为什么我们不能得出结论 array是一个指针(指向第一个元素的内存地址)?我知道这不可能是事实,但他们的行为是一样的?
谢谢

最佳答案

我发现一个例子澄清。我这里有一些 foo重载接受您在代码中使用的版本。

#include <iostream>
#include <string>

template<size_t N>
std::string foo(const int(&)[N]) {
return std::string(" int(&)[") + std::to_string(N) + "]\n";
}

template<size_t N>
std::string foo(const int(*)[N]) {
return std::string(" int(*)[") + std::to_string(N) + "]\n";
}

std::string foo(const int*) {
return " int*\n";
}

std::string foo(int) {
return " int\n";
}

int main() {
int array [] = {8, 7, 6, 5, 4};
std::cout << array << foo(array);
std::cout << &array << foo(&array);
std::cout << *(&array) << foo(*(&array));
std::cout << *array << foo(*array);
}
可能的输出:
0x7ffeaf43a610 int(&)[5]
0x7ffeaf43a610 int(*)[5]
0x7ffeaf43a610 int(&)[5]
8 int
如您所见,通过这种重载组合,没有一个版本会衰减为 int* .

关于c++ - 左值和右值与 C++ 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63941638/

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