c++ - 复合模式中的循环依赖
问题描述
我显然面临循环依赖问题,因为 Document 和他的孩子使用指向 Ambit 的指针,反之亦然;我已经阅读了关于堆栈溢出的已解决问题,并且我在适当的部分遵循了本指南,但代码仍然显示问题,特别是没有找到对构造函数和析构函数的引用。我想指出 Document 和 Ambit 是纯抽象类。为了更清楚,代码如下:
- 文档.h
#ifndef DOCUMENT_H_
#define DOCUMENT_H_
class Ambit; //forward declaration
class Document{
public:
Document();
virtual ~Document();
virtual void addDocument(Document*);
virtual void showSelf();
virtual void showRelated();
virtual void setAnnotation(Ambit*);
};
#endif /* DOCUMENT_H_ */
- 范围.h
#ifndef AMBIT_H_
#define AMBIT_H_
class Document; //forward declaration
class Ambit{
public:
Ambit();
virtual ~Ambit();
virtual void addAmbit(Ambit*);
virtual void showSelfA();
virtual void showRelatedA();
virtual void setAnnotationA(Document*);
};
#endif /* AMBIT_H_ */
- CompAmbit.h
#ifndef COMPAMBIT_H_
#define COMPAMBIT_H_
#include <iostream>
#include <vector>
#include "Ambit.h"
using namespace std;
class CompAmbit : public Ambit{
private:
string ambName;
Document* annotation;
vector<Ambit*> ambitVec;
public:
CompAmbit(string);
~CompAmbit();
void addAmbit(Ambit*);
void showSelfA();
void showRelatedA();
void setAnnotationA(Document*);
};
#endif /* COMPAMBIT_H_ */
- CompAmbit.cpp
#include<iostream>
#include<vector>
#include "CompAmbit.h"
#include "Document.h" //added header to Document for the knowledge of showSelf()
using namespace std;
CompAmbit::CompAmbit(string newName){ // @suppress("Class members should be properly initialized")
ambName = newName;
};
CompAmbit::~CompAmbit(){};
void CompAmbit::addAmbit(Ambit* newAmbit){
ambitVec.push_back(newAmbit);
};
void CompAmbit::setAnnotationA(Document* newAnnotation){
annotation = newAnnotation;
};
void CompAmbit::showSelfA(){
for(unsigned int i = 0; i<ambitVec.size(); i++ ){
ambitVec[i]->showSelfA();
};
};
void CompAmbit::showRelatedA(){
annotation->showSelf();
};
Section.h 和 Section.cpp 类似于 CompAmbit。
如您所见,我需要相互引用才能使用注释变量中的指针调用函数showSelf()(或 showSelfA()) 。
我使用了前向声明,并在CompAmbit.cpp中将标题添加到 Document 以了解showSelf()。我认为我到目前为止表现良好,但在编译时收到以下错误:
CompAmbit.cpp:14: undefined reference to Ambit::Ambit() //14 is line of CompAmbit constructor CompAmbit.cpp:14: undefined reference to Ambit::~Ambit()
CompAmbit.cpp:18: undefined reference to Ambit::~Ambit() //18 是 CompAmbit 析构函数行
和 Section 的类似错误。
我在哪里做错了?
注意:我省略了叶子代码以保持问题简短。
编辑:我忘了说在 CompAmbit.cpp 中添加 #include "Document.h" 后会弹出错误
编辑:通过阅读这篇文章什么是未定义的引用/未解决的外部符号错误,我该如何解决? 我发现我没有定义构造函数和析构函数;出于某种原因,我认为纯虚拟类不需要任何定义;我只是通过替换Ambit()来解决;与范围(){};,析构函数和 Document.h 文件中的相同。