在 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/