2016-04-13 49 views
0

嗨,我试图创建一个工厂方法,返回类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(); 
     ^
+1

将'factory.h'包含在'A.h'中有什么意义? – SergeyA

+0

我打电话给Factory :: fact();来自A :: a() – Zindan

回答

0

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.hFactory.cpp

+0

'Factory.cpp:在静态成员函数'static A * Factory :: fact()'中: Factory.cpp:3:13:错误:'A_CHILD_ONE'之前的预期类型说明符 return新的A_CHILD_ONE; ^ Factory.cpp:3:13:error:expected';'before'A_CHILD_ONE' Factory.cpp:3:13:error:'A_CHILD_ONE'未在此范围内声明' – Zindan

+0

btw,什么意思是什么时候您将Factory.h放在A.cpp中,而不是在Ah中? – Zindan

+0

@Zindan据我所知,从'Factory.h'中删除'#include AChildOne.h'后出现这个错误。我使得答案更加精确:'#include AChildOne.h'应该在'Factory.cpp'中。 –