2012-11-07 4 views
1

C++의 수퍼 클래스 내부에서 하위 클래스를 참조 할 때 약간 혼란 스럽습니다. 자바 주어진 예를 들어 : ComplexEntity가 entity.It works.In에게 내가 getCentity() 오류를 호출하지 하위 클래스를 확장슈퍼 클래스의 C++ 참조 하위 클래스

public class Entity { 


    protected ComplexEntity _ce; 

    public Entity() { 

    } 

    public ComplexEntity getCentity() { 
    return _ce; 
    } 
} 

.

이제, C에서 + +를 내가 그런 걸 쓸 때 :

#pragma once 

#include "maininclude.h" 
#include "ExtendedEntity.h" 
using namespace std; 

class EntityBase 
{ 
public: 
    EntityBase(void); 
    EntityBase(const string &name); 

    ~EntityBase(void); 

protected: 

    ExtendedEntity* _extc; 
    string _name; 
}; 

내가 무엇입니까 컴파일러 오류 : 그런 일이 않습니다이 Entity.Why에서 상속 된 클래스에서

error C2504: 'Entity' : base class undefined 

를?

C++에서는 완전히 받아 들일 수 있습니까?

5 월 엔티티는 추상적이어야합니다. 가능한 해결 방법에 대한 제안을 받고 싶습니다.

+3

당신이 보여줄 수있는 C++ 코드가 있습니까? – jrok

+0

1 분주세요 –

답변

3

당신은 위키 백과에서 CRTP, 잘라 내기/붙여 넣기 사용을 고려할 수 있습니다

// The Curiously Recurring Template Pattern (CRTP) 
template<class Derived> 
class Base 
{ 
    Derived* getDerived() { return static_cast<Derived*>(this); } 
}; 

class Derived : public Base<Derived> 
{ 
    // ... 
}; 
+0

이 패턴은 파생 클래스가 기본 클래스의 참조와 다른 유형 인 경우 문제가 될 수 있습니다. 나는 하나의 기지에서만 파생 된 것이 좋은 곳이라고 생각합니다. 아, 죄송합니다, 틀렸어. 이 코멘트를 무시하십시오. –

1

와 그 모든 슈퍼 클래스의 모든 멤버의 크기를 알 필요가 C++에서 클래스를. 클래스 Entity은 클래스 ComplexEntity이 클래스 Entity 이전에 정의되어 있지 않으면 서브 클래스 ComplexEntity의 크기를 알지 못합니다. 그러나 클래스 ComplexEntity은 수퍼 클래스 Entity의 크기를 알지 못합니다.

이 문제는 C++에서 발생합니다. 클래스 멤버는 간단한 오프셋 계산을 사용하여 액세스되기 때문입니다. 당신은 회원으로 포인터를 파생 클래스를 선언하고 사용하는 기대로,이 문제를 해결할 수 있습니다

class Extended; // declare the derived class 

class Base { // define the base class 
    Extended* e; // you cannot use Extended e here, 
       // because the class is not defined yet. 
}; 

class Extended : public Base {}; // define the derived class 
+0

Entity가 포인터로 ExtendedEntity를 보유하므로 Entity는 ExtendedEntity에 대해 알 필요가 없습니다. – bames53

1

코드는 같다 다음

struct D : B {}; // error: B doesn't mean anything at this point 

struct B { 
    D *d; 
}; 

귀하의 헤더 ExtendedEntity.h이 정의를 사용하려고 Entity before Entity가 정의됩니다.

당신이 당신의 코드를 변경해야

:

struct D; 

struct B { 
    D *d; 
}; 

struct D : B {}; 
+0

Entity 헤더 앞에 ExtendedEntity의 변수를 넣어야한다는 것을 의미합니까? 구조체 예제와 함께 가져 오지 마십시오 ... –

+0

OK, 이제 의미를 알았습니다. @ 오스왈드는 아주 묘사적인 방식으로 표현했습니다. 감사합니다. –

관련 문제