平等与C++ 中数组上使用的赋值运算符
我被布置了一个家庭作业问题,这让我很困惑。问题是:
在 C++ 中,相等测试 == 可能是 应用于数组,但赋值 运算符 = 不能应用于 数组。解释一下原因。
这让我很困惑,因为我的理解是 ==
运算符只会比较前两个元素的地址(如果两个数组实际上保存在不同的内存位置,当然会有所不同) 。而 =
运算符,当像 array1 = array2;
使用时,只会导致 array1 指向与 array2 相同的内存位置。
我在这里缺少什么?似乎可以使用任一运算符,但都不会产生这些运算符通常想要的结果。
I was given a homework question that really confuses me. The question is:
In C++ the equality test == may be
applied to arrays, but the assignment
operator = cannot be applied to
arrays. Explain why.
This confuses me, because my understanding is that the ==
operator would just compare the addresses of the first two elements (which if two arrays were in fact held in separate memory locations, of course would be different). And the =
operator, when used like array1 = array2;
would just cause array1 to point to the same memory location as array2 does.
What am I missing here? It seems as though either operator can be used, but neither would produce the results typically intended by those operators.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是正确的:如果您使用
==
比较两个数组,它将比较数组的地址,因此它会仅当将数组与其自身(或指向相同类型元素的指针)进行比较时,才会产生true
。请参阅下面的描述了解原因。这是不正确的,因为数组不是指针。
array1
无法指向与array2
相同的内存位置,因为array1
不是指针,而是元素数组。数组是元素的序列。在大多数情况下,数组的名称会隐式转换为指向其初始元素的指针。这就是为什么您可以执行以下操作:
array1 = array2;
不起作用,因为数组不可分配(主要是出于历史原因;我从未听说过令人信服的技术原因为什么不允许这样做:在 C 中从来没有被允许,并且 C 已经存在了几十年了,在 为什么 C 支持结构体中数组的成员分配,但一般不支持?)。以下程序将无法编译:
对于“可分配”数组,您可以使用 Boost (
boost::array
)、C++ TR1 (std::tr1::array
),或 C++0x (std::array
)。它实际上是一个包含数组的类;它可以被复制,并且提供了标准库容器的许多优点以及数组的性能特征以及在需要时将其数据用作数组的能力。This is correct: if you compare two arrays using
==
, it will compare the addresses of the arrays, so it will only yieldtrue
if you compare an array with itself (or with a pointer to an element of the same type). See the description below for why.This is not correct because an array is not a pointer.
array1
can't point to the same memory location asarray2
becausearray1
isn't a pointer, it's an array of elements.An array is a sequence of elements. In most contexts, the name of an array is implicitly converted to a pointer to its initial element. This is why you can do things like:
array1 = array2;
won't work because arrays are not assignable (mostly for historical reasons; I've never heard a convincing technical reason why it isn't allowed: it was never allowed in C, and C has been around for decades. There's some discussion of this in the comments and answers to Why does C support memberwise assignment of arrays within structs but not generally?).The following program will not compile:
For an "assignable" array, you can use the
array
container-like class found in Boost (boost::array
), C++ TR1 (std::tr1::array
), or C++0x (std::array
). It is actually a class that contains an array; it can be copied and it provides many of the benefits of the Standard Library containers plus the performance characteristics of an array and the ability to use its data as an array when you need to.