问题描述
我在MSVC中查看了CList定义和文档。我没有看到 CList& operator =(const CList&);
。
I've looked up the CList definition in MSVC afxtempl.h
and document on MSDN. I did not see the CList& operator=(const CList&);
is defined.
我可以直接使用 operator =
来复制这样的CList对象吗?
Can I directly use operator=
to copy a CList object like this?
CList<int> a = b;
或者我应该从头手动迭代源CList
到目标CList上的 tail
和 AddTail
?
Or I should iterate the source CList manually from head
to tail
and AddTail
on the target CList?
for(POSITION pos = a.HeadPosition(); pos; )
{
const auto& item = a.GetNext(pos);
b.AddTail(item);
}
任何建议都会有所帮助。
谢谢。
Any suggestions will be helpful.Thanks.
推荐答案
如果未定义副本赋值操作符, t。这是真的 CList
,正如你已经观察到的,所以不,你不能只使用 operator =
复制 CList
对象。如果你想要一个深层副本的集合,你将需要写一个函数来这样做手动。
If the copy assignment operator isn't defined, then it isn't defined and can't be used. That's true for CList
, as you've already observed, so no, you can't just use operator=
to copy a CList
object. If you want a deep copy of the collection, you will need to write a function to do so manually.
但考虑你是否真的想要一个深层副本。大多数时候,你想通过引用传递集合类型,而不是通过值。这在MFC中尤其如此,它们可以包含从 CObject
派生的对象,不一定可以复制。实际上,您会注意到, CObject
类使用私有副本构造函数和赋值运算符显式禁止复制:
But consider whether you really want a deep copy. Most of the time, you'll want to pass collection types by reference, rather than by value. This is especially true in MFC, where they can contain objects derived from CObject
that can't necessarily be copied. In fact, you'll notice that copying is explicitly disallowed by the CObject
class, using a private copy constructor and assignment operator:
// Disable the copy constructor and assignment by default so you will get
// compiler errors instead of unexpected behaviour if you pass objects
// by value or assign objects.
private:
CObject(const CObject& objectSrc); // no implementation
void operator=(const CObject& objectSrc); // no implementation
这篇关于MFC CList是否支持复制分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!