【问题标题】:C++ reference sub class in super class超类中的 C++ 引用子类
【发布时间】:2012-11-08 02:01:48
【问题描述】:

我对在 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++ 中是完全不能接受的吗?

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

【问题讨论】:

  • 你有 C++ 代码要展示吗?

标签: c++ oop inheritance


【解决方案1】:

您可以考虑使用CRTP,从维基百科剪切/粘贴:

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

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

【讨论】:

  • 如果派生的类型与基类中对它的引用的类型不同,则此模式可能会出现问题。我认为只有一个派生到一个基地是好的。不,对不起,我错了。放弃此评论
【解决方案2】:

你的代码如下:

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 {};

【讨论】:

  • 你的意思是我必须在 Entity 标头之前放置一个 ExtendedEntity 的变量吗?不要通过结构示例来获取它...
  • 好的,现在我明白你的意思了。 @Oswald 以一种非常具有描述性的方式说出来。谢谢。
【解决方案3】:

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

【讨论】:

  • Entity 不需要知道关于 ExtendedEntity 的任何信息,因为 Entity 通过指针持有一个 ExtendedEntity。
猜你喜欢
  • 2015-03-09
  • 1970-01-01
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
相关资源
最近更新 更多