MFC中CArray的嵌套问题

来源:互联网 发布:手机身份证复印软件 编辑:程序博客网 时间:2024/05/22 00:28
 

当CArray 嵌套时候,许多情况下会发生C2448;C2664;C2582这样的错误。

并且指示CArray的内部错误。

在KB231995中,微软描述了问题,并且简要的诉说了解决方案。

英文版本:  http://support.microsoft.com/kb/231995/en

中文机器翻译版本:http://support.microsoft.com/kb/231995/zh-cn

事情的缘由有2个。

1.对于没有赋值操作符(operate =)的复合数据结构(struct和class等等),编译器会自动生成一个默认的赋值操作符,她会枚举数据结构的所有成员,然后复制。 于是,对于一个包含CArray的复合数据结构,默认的赋值操作符会把CArray自身的数据结构一并复制。

2.CArray继承自CObject。对于CObject和CArray的私有成员,任何复制的请求都会被拒绝。(实际上,你也不应该复制CArray自身,相反,复制CArray包含的用户数据。一般可以使用CArray::Copy)

于是CArray嵌套就会出现以上错误。

解决建议实现一个拷贝构造函数和一个赋值操作符。

举例来自:Effective C++

class string {
public:
  string(const string& str);

string& operate = (const string& str);

}

在拷贝构造函数中可以具体实现,在赋值操作符中可以简单的写:

string::string(str);

return *this;

就简洁的实现了赋值。

 

#include <afxtempl.h>

struct A
{
int i;
int j;
};

class B
{

public:
B();
~B();

// Need to define copy ctor and assignment operator.

B(const B& b)

{
// Your copy ctor body goes here.

arrayA.Copy(b.arrayA);

}

/* const B& */ void operator= (const B& b)

{
// Your assignment operator body goes here.

arrayA.Copy(b.arrayA);

return *this;
}


protected:
CArray<A, A> arrayA;
};

B::B(){}
B::~B(){}

class C
{

public:
C();
~C();
void addElement();

protected:
CArray<B, B> arrayB;
};

C::C(){}
C::~C(){}
void C::addElement()
{
B temp;
arrayB.Add(temp);
}

void main()
{
}

这个问题一直都解决,今天解决了,所以放到博客里面,主要要多看看微软的一些文章!

原创粉丝点击