C++ 引用父类(super class)中的子类

标签 c++ oop inheritance

在 C++ 中引用父类(super class)中的子类时,我有点困惑。 例如,给定 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++中是完全不能接受的吗?

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

最佳答案

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

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

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

关于C++ 引用父类(super class)中的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13275150/

相关文章:

c++ - 在 C++ 中将双数组初始化为零时崩溃

c++ - 如何在 C++ 中自动从 QComBox 获取当前 QString 文本?

oop - 如果 Address 继承自 PhoneNumber,它违反了哪些 OOP 原则?

javascript - Typescript - 内部模块中的导入声明不能引用外部模块

c++ - 多态性和默认值 : can co-exist?

c++ - 未捕获的异常

c++ - 创建采用可变数量的参数和数据类型的函数

objective-c - OOP:设计菜单系统

Javascript 继承问题

c++ - 额外的继承对对象结构或实例化有什么影响吗?