难以理解循环声明

Having trouble to understand circular declaration

本文关键字:循环 声明      更新时间:2023-10-16

嗨,我正在尝试创建一个工厂方法,它返回类a的派生类,我在理解循环声明时遇到了问题,希望你能帮我解决这个问题。

谢谢。

AChildOne.cpp


#include "AChildOne.h"

AChildOne.h


#ifndef ACHILDONE_H
#define ACHILDONE_H
#include "A.h"
class A_CHILD_ONE : public A {
};
#endif

A.cpp


#include "A.h"
void A::a(){
    Factory::fact();
};

A.h


#ifndef A_H
#define A_H
#include "Factory.h"
class A {
    public:
      static void a();
};
#endif

Factory.cpp


#include "Factory.h"
A *Factory::fact(){
    return new A_CHILD_ONE;
}

Factory.h


#ifndef FACTORY_H
#define FACTORY_H
#include "A.h"
#include "AChildOne.h"
class Factory {
    public:
     static A *fact();
};
#endif

编译错误

g++ A.cpp Factory.cpp AChildOne.cpp -o test
In file included from Factory.h:5:0,
                 from A.h:4,
                 from A.cpp:1:
AChildOne.h:5:30: error: expected class-name before ‘{’ token
 class A_CHILD_ONE : public A {
                              ^
In file included from A.h:4:0,
                 from A.cpp:1:
Factory.h:9:10: error: ‘A’ does not name a type
   static A *fact();
          ^
A.cpp: In static member function ‘static void A::a()’:
A.cpp:4:2: error: ‘fact’ is not a member of ‘Factory’
  Factory::fact();
  ^
In file included from A.h:4:0,
                 from AChildOne.h:3,
                 from AChildOne.cpp:1:
Factory.h:9:10: error: ‘A’ does not name a type
   static A *fact();
          ^

Factory.h中,您尝试包含A.h;在A.h中,您尝试包含Factory.h

Factory.h包含到A.cpp中并从A.h中删除应该会有所帮助。

Factory声明依赖于A接口。A声明不依赖于Factory声明,但A定义依赖于。

此外,Factory.h不需要知道AChildOne.h,但Factory.cpp需要知道。因此,将#include AChildOne.h移动到Factory.cpp