2017-11-23 111 views
0

순환 종속성 및 상속과 관련된 C++의 문제점이 있습니다.C++에서 순환 종속성 및 상속 컴파일 오류

나는 디자인을 부분적으로 구현 했으므로 문제가 발생한 곳에서 필자는 pesudocode를 사용합니다.

첫 번째 부분은 여기까지, 프로그램이 경고 그런

없이 컴파일

//app.h 

include rel.h 

class Rel; // forward declaration 

class App { 
    shared_ptr<Rel> //member variable 
} 

//rel.h 

include app.h 

class App; //forward declaration 

class Rel { 
    shared_ptr<App> //member variable 
} 

, 나는 다음과 같이 상속을 추가 할 :

//app.h 

include rel.h 
include drel.h 

class Rel; // forward declaration 
class DRel // forward declaration 

class App { 
    shared_ptr<Rel> //member variable 
    shared_ptr<DRel> //member variable 
} 

//rel.h (the same as before) 

include app.h 

class App; //forward declaration 

class Rel { 
    shared_ptr<App> //member variable 
} 

//drel.h 

include app.h 
include rel.h 

class App; //forward declaration 

class DRel: Rel { // compile error here: expected class name before { token 
    shared_ptr<App> //member variable 
} 

당신이 볼 때, 컴파일러는 "token"(즉, Rel)이 해결되지 않았지만 상속이없는 첫 번째 코드가 작동하고 두 번째 코드가 작동하지 않는 이유는 무엇입니까? 어떻게 해결할 수 있습니까? 그것은 "잘못된"패턴입니까?

내가 사용하고 C++ 14

나는 데 문제에 관한 질문을 많이 알고,하지만 난 내 특정 문제에 대한 답을 찾을 수 없습니다. 어쩌면 나는 그것을 볼 수 없을 것입니다 ...

+3

마 실제 헤더에도 경비원이 포함되어 있지 않습니까? 만약 당신이'App'을 선언했다면'Rel' 헤더에'app.h'를 포함하지 말고 대신'rel.cpp'에 그것을 포함시켜야합니다. – Darhuuk

+0

@Darhuuk와 합의했습니다. 분할 헤더에서 모든 것을 동일한 헤더로 옮기고 그 결과가 향상되는지보십시오. – TinyTheBrontosaurus

+2

내 생각 엔 두 번째 .h 파일이로드되지 않도록 가드가 동일하다는 것입니다. 실제 코드가 게시 된 경우 더 쉬울 것입니다. – TinyTheBrontosaurus

답변

1

선언 한 모든 변수는 App, Rel 및 DRel이 차지하는 공간을 알 필요가 없기 때문에 문제의 헤더가 #include 일 필요가 없습니다. 당신이하는 것처럼 이름을 선언해야합니다.

그래서 당신이 원래의 헤더는 다음과 같이 위해서 #ifdefs에 의해 보호 될 필요가 파일

#include "A" 
#include "B" 

C::C() { ... } 
0

으로 다음

class A; 
class B; 

class C { 
    std::shared_ptr<A> ptra; 
    std::shared_ptr<B> ptrb; 
}; 

그리고 당신의 .cpp 당신에게 .h 있습니다

#ifndef CYCLIC_DEPENDECY_1 
#define CYCLIC_DEPENDECY_1 
#include "cyclic_dependency2.h" 
class Rel; // forward declaration 

class App { 
    std::shared_ptr<Rel> test; //member variable 
}; 
#endif 




#ifndef CYCLIC_DEPENDECY_2 
#define CYCLIC_DEPENDECY_2 
#include "cyclic_dependency1.h" 

class App; //forward declaration 

class Rel { 
    std::shared_ptr<App> test;//member variable 
}; 
#endif 



#include <iostream> 
#include <memory> 
#include "cyclic_dependency2.h" 

class Rel; // forward declaration 
class DRel; // forward declaration 

class DRel: Rel { 
    std::shared_ptr<App> test ;//member variable 
}; 

main() 
{ 
}