1

C++ でスーパー クラス内のサブクラスを参照する際に少し混乱しています。たとえば、指定された Java :

public class Entity {


  protected ComplexEntity _ce;

  public Entity() {

  }

  public ComplexEntity getCentity() {
    return _ce;
  }
}

ComplexEntityがエンティティを拡張する場所.それは機能します.サブクラスでは、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  

このエンティティから継承するクラスでは、なぜそれが起こるのですか?

C ++では完全に受け入れられませんか?

エンティティは抽象でなければなりませんか?可能な回避策についての提案を得たいと思います。

4

3 に答える 3

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>
{
    // ...
};
于 2012-11-07T17:47:13.410 に答える
1

C++ のクラスは、そのすべてのメンバーとそのすべてのスーパークラスのサイズを知る必要があります。classが class の前に定義されていない限り、 ClassEntityはそのサブクラスのサイズを知りません。しかし、クラスはそのスーパークラスのサイズを知りません。ComplexEntityComplexEntityEntityComplexEntityEntity

この問題は 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
于 2012-11-07T17:48:58.440 に答える
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 {};
于 2012-11-07T17:55:15.400 に答える