2012-11-07 37 views
1

我在C++中引用超类内的子类时有点困惑。 例如,给定的Java:超级类中的C++引用子类

public class Entity { 


    protected ComplexEntity _ce; 

    public Entity() { 

    } 

    public ComplexEntity getCentity() { 
    return _ce; 
    } 
} 

凡ComplexEntity扩展entity.It works.In子类我称之为getCentity()没有错误。

现在,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; 
}; 

我正在编译器错误:

error C2504: 'Entity' : base class undefined 

在从该Entity.Why继承发生的呢类?

在C++中是完全不可接受的吗?

可能实体必须是抽象的吗? 我想获得有关可能的解决方法的建议。

+3

你有任何C++代码显示? – jrok

+0

请一分钟 –

回答

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 A类++需要知道它的所有成员的规模和它的所有超。类Entity不知道它的子类ComplexEntity的大小,除非类ComplexEntity在类Entity之前定义。但是,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

实体不需要知道有关ExtendedEntity的任何信息,因为Entity通过指针保存ExtendedEntity。 – bames53

1

你的代码是这样的:

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

struct B { 
    D *d; 
}; 

页眉ExtendedEntity.h试图使用定义定义实体之前的实体。

你需要对你的代码改成这样:

struct D; 

struct B { 
    D *d; 
}; 

struct D : B {}; 
+0

你的意思是我必须在Entity头之前放置一个ExtendedEntity的变量吗?不要用结构的例子来得到它...... –

+0

好的,现在我明白你的意思了。 @Oswald把它描述得很具描述性。谢谢。 –