我收到了一个让我非常困惑的家庭作业问题。问题是:
In C++ the equality test == may be applied to arrays, but the assignment operator = cannot be applied to arrays. Explain why.
这让我很困惑,因为我的理解是 ==
运算符只会比较前两个元素的地址(如果两个数组实际上保存在不同的内存位置,当然会不同)。而 =
运算符,当像 array1 = array2;
一样使用时,只会导致 array1 指向与 array2 相同的内存位置。
我在这里缺少什么?似乎可以使用任一运算符,但两者都不会产生这些运算符通常想要的结果。
最佳答案
my understanding is that the == operator would just compare the addresses of the first two elements
这是正确的:如果你使用 ==
比较两个数组,它将比较数组的地址,所以如果你比较一个数组,它只会产生 true
与自身(或与指向相同类型元素的指针)。请参阅下面的说明了解原因。
the = operator, when used like array1 = array2; would just cause array1 to point to the same memory location as array2 does.
这是不正确的,因为数组不是指针。 array1
不能指向与 array2
相同的内存位置,因为 array1
不是指针,它是一个元素数组。
数组是元素的序列。在大多数情况下,数组的名称被隐式转换为指向其初始元素的指针。这就是为什么您可以执行以下操作:
void f(int*);
int data[10];
int* p = data; // this is the same as 'int* p = &data[0];'
f(data); // this is the same as 'f(&data[0]);'
array1 = array2;
不起作用,因为数组不可分配(主要是出于历史原因;我从未听说过一个令人信服的技术原因为什么不允许它:它从未被允许C,而 C 已经存在了几十年。在 Why does C support memberwise assignment of arrays within structs but not generally? 的评论和答案中有一些讨论。
以下程序将无法编译:
int main() {
int a[10], b[10];
a = b;
}
对于“可赋值”数组,您可以使用 Boost (boost::array
)、C++ TR1 (std) 中的
) 或 C++0x (array
类容器类::tr1::arraystd::array
)。它实际上是一个包含数组的类;它可以被复制,它提供了标准库容器的许多优点以及数组的性能特征以及在需要时将其数据用作数组的能力。
关于c++ - C++ 中用于数组的等式和赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5345705/