本文介绍了C ++循环引用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个类: DataObject DataElement DataObject 保存指向(仅) DataElement s和 DataElement 包含指向几种类型的指针,其中包括 DataObject

I have 2 classes: DataObject and DataElement. DataObject holds pointers to (only) DataElements, and a DataElement contains pointers to several types, among which a DataObject.

这以前没问题,因为我仅使用指向 DataElement 中的 DataObject s的指针,因此 DataObject DataElement 的标题中的c $ c>就足够了。

This used to be no problem, since I only use pointers to DataObjects in DataElement, so a forward declaration of DataObject in the header of DataElement is enough.

现在,我尝试添加析构函数到 DataElement ,其中需要删除 DataObject 。对此,编译器说:

Now, however, I try to add a destructor to DataElement, in which I need a delete on a DataObject. On this the compiler says:

dataelement/destructor.cc: In destructor ‘DataElement::~DataElement()’:
dataelement/destructor.cc:8: warning: possible problem detected in invocation of delete operator:
dataelement/destructor.cc:8: warning: invalid use of incomplete type ‘struct DataObject’
dataelement/dataelement.h:7: warning: forward declaration of ‘struct DataObject’
dataelement/destructor.cc:8: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.

我该如何解决?前向声明显然还不够,尽管我不能包含 DataObject 的完整标题,因为这又使我有了循环依赖关系。

How can I solve this? A forward declaration is apparently not enough, while I cannot include the complete header for DataObject, since that gives me a circular dependency again.

谢谢!

推荐答案

在包含两个标头的.cpp文件中定义析构函数。

Define the destructor in a .cpp file that includes both headers.

这篇关于C ++循环引用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-11 03:34