c++中的循环依赖帮助
Circular dependency assistance in C++
我有一个类似于下面的代码,但我不知道如何使它工作
我已经搜索了它,看起来是关于循环依赖的东西,但现在,我已经尝试了一些例子,但只能使用依赖2。
相反,这一个,我有"Ctrl"类,许多类依赖于它们(CtrlA和CtrlB是相互依赖的,Ax类都需要Ctrl),但也需要Ctrl文件的一些类(CtrlA需要Ax类)。另外,我有一个继承类(A2继承A3)。
CtrlA.h
#ifndef CTRLA
#define CTRLA
#include "CtrlB.h"
#include "A1.h"
class CtrlB;
class A1;
class CtrlA{
protected:
A1 x;
public:
void op1(CtrlB b){
a.op1(this, b);
}
void op2(){}
};
#endif
CtrlB.h
#ifndef CTRLB
#define CTRLB
#include "CtrlA.h"
class CtrlA;
class CtrlB{
protected:
public:
void op1(){}
void op2(CtrlA a){
a.op1(this);
}
};
#endif
A1.h
#ifndef A1
#define A1
#include "CtrlA.h"
#include "CtrlB.h"
#include "A2.h"
class CtrlA;
class CtrlB;
class A1{
protected:
A2 x1;
public:
void op1(CtrlA a, CtrlB b){
x1.op1(this, b);
}
};
#endif
A2.h
#ifndef A2
#define A2
#include "CtrlA.h"
#include "CtrlB.h"
#include "A3.h"
class CtrlA;
class CtrlB;
class A2:public A3{
protected:
public:
void op1(CtrlA a, CtrlB b){
a.op2();
b.op1();
}
};
#endif
A3.h
#ifndef A3
#define A3
#include "CtrlA.h"
#include "CtrlB.h"
class CtrlA;
class CtrlB;
class A3{
protected:
public:
virtual void op1(CtrlA a, CtrlB b) = 0;
};
#endif
main.cpp
#include "CtrlA.h"
#include "CtrlB.h"
int main(){
int i;
}
我将非常感激如果有人可以帮助我纠正代码,使它可以工作。
对于CtrlA.h, CtrlB.h, A1.h和A3.h,如果您使用前向声明(您排序了)并使用引用或指针(您没有),则不需要#include任何内容:
CtrlA.h
#ifndef CTRLA
#define CTRLA
class CtrlB;
class A1;
class CtrlA {
protected:
A1* x;
public:
/* Use a CtrlB reference instead -- probably wanted to do this anyway
/* since you don't want to copy CtrlB when called */
void op1(CtrlB& b); /* Move function body to .cpp file */
void op2(){}
};
#endif
A1.h
#ifndef A1
#define A1
class CtrlA;
class CtrlB;
class A2; /* You have to use forward declaration on every class you use below */
class A1{
protected:
A2* x1;
public:
void op1(CtrlA& a, CtrlB& b); /* Again, use references and move function
bodies to .cpp */
};
#endif
但是对于A2.h,你继承了A3,所以你必须#include A3.h
A2.h
#ifndef A2
#define A2
#include "A3.h"
class CtrlA;
class CtrlB;
class A2:public A3{
protected:
public:
void op1(CtrlA& a, CtrlB& b);
};
#endif
剩下main.cpp,你可以把它们都包含进去:
main.cpp
#include "CtrlA.h"
#include "CtrlB.h"
#include "A1.h"
#include "A2.h"
#include "A3.h"
int main(){
int i;
}
希望有帮助!这里有一个关于前向声明以及何时/如何使用它的快速参考。
编辑:感谢Pablo指出我的错误。不能使用前向声明的类作为成员对象,只能使用引用或指针。我把上面的例子改为使用指针。
我的建议:使用更多的指针和尽可能多的前向声明(并避免在.h文件中包含其他头文件)。#将它们包含在需要实现的.cpp文件中。)
<标题> CtrlA.h h1> 能将不完整类型声明为成员。你会在这个问题的第二个答案中找到一些有用的信息
标题>相关文章:
- 如何从C++中的依赖类型中获得它所依赖的类型
- 需要帮助设置在C++中使用的Potrace
- 在指针的帮助下,文本文件中单词的频率
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 如何在Qbutton的帮助下更改Q对话框的宽度
- 将依赖名称显式标记为类型名和模板的奇怪之处
- 需要帮助将结构数组传递给函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- C++GTKMM gui循环依赖关系
- 通过ccmake在cmake中缓存依赖选项
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 当基类是依赖类型时,这是一个缺陷吗
- 从不同的附加依赖项中识别等同命名的函数
- 如何在 CMake 中对目标依赖项进行分组?
- cmake:构建依赖于非源文件.Qt帮助生成
- 我需要帮助开发多态引擎 - 指令依赖树
- Wallaroo依赖项和静态帮助程序类
- c++中的循环依赖帮助
- 在DLL搜索路径中添加路径以帮助执行依赖于DLL的EXE