c++中的循环依赖帮助

Circular dependency assistance in C++

本文关键字:依赖 帮助 循环 c++      更新时间:2023-10-16

我有一个类似于下面的代码,但我不知道如何使它工作

我已经搜索了它,看起来是关于循环依赖的东西,但现在,我已经尝试了一些例子,但只能使用依赖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> 能将不完整类型声明为成员。

你会在这个问题的第二个答案中找到一些有用的信息