问题描述
我显然面临循环依赖问题,因为Document和他的孩子使用指向Ambit的指针,反之亦然;我已经在此处阅读了有关堆栈溢出的已解决问题,并且我遵循了this guide in the proper section,但是代码仍然显示出问题,尤其是未找到对构造函数和析构函数的引用。我想指出Document和Ambit是纯抽象类。 为了更清晰,代码如下:
- Document.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_ */
- Ambit.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类似。
如您所见,我需要相互引用才能使用 annotation 变量中的指针来调用函数 showSelf()(或showSelfA())。
我使用了前向声明,并在 CompAmbit.cpp 中添加了Document的标头,以了解 showSelf()的知识。我认为到目前为止我的表现还不错,但是在编译时收到以下错误:
CompAmbit.cpp:14:对Ambit :: Ambit()的未定义引用// 14是CompAmbit构造函数的行
CompAmbit.cpp:14:对Ambit ::〜Ambit()的未定义引用
CompAmbit.cpp:18:未定义对Ambit :: ~~ Ambit()// 18是CompAmbit析构函数的行
和Section的类似错误。
我在哪里做错了?
注意:为了使问题简短,我省略了叶代码。
编辑:我忘了说在CompAmbit.cpp中添加#include“ Document.h”之后弹出错误提示
编辑:通过阅读本文What is an undefined reference/unresolved external symbol error and how do I fix it? ,我发现我没有定义构造函数和析构函数;由于某种原因,我认为纯虚拟类不需要任何定义;我只是通过替换 Ambit()解决了;与 Ambit(){}; 相同,对于析构函数和Document.h文件相同。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)