【发布时间】:2020-05-03 11:07:11
【问题描述】:
我正在创建粒子系统,我希望能够选择将在屏幕上显示的对象类型(例如简单的像素或圆形)。我有一个存储所有参数的类(ParticleSettings),但没有存储点或圆形等的实体。我认为我可以创建纯虚拟类(ParticlesInterface)作为基类,其派生类如ParticlesVertex 或 ParticlesCircles 用于存储这些可绘制对象。是这样的:
class ParticlesInterface
{
protected:
std::vector<ParticleSettings> m_particleAttributes;
public:
ParticlesInterface(long int amount = 100, sf::Vector2f position = { 0.0,0.0 });
const std::vector<ParticleSettings>& getParticleAttributes() { return m_particleAttributes; }
...
}
和:
class ParticlesVertex : public ParticlesInterface
{
private:
std::vector<sf::Vertex> m_particleVertex;
public:
ParticlesVertex(long int amount = 100, sf::Vector2f position = { 0.0,0.0 });
std::vector<sf::Vertex>& getParticleVertex() { return m_particleVertex; }
...
}
所以...我知道我无法通过使用多态来访问 getParticleVertex() 方法。我真的很想拥有这种访问权限。我想问是否有更好的解决方案。我在决定如何将所有这些联系在一起时遇到了非常糟糕的时光。我的意思是我也在考虑使用模板类,但我需要它是动态绑定而不是静态的。我认为这种多态性的想法是可以的,但我真的需要在该选项中访问该方法。你能帮我怎么做吗?我想知道这里最好的方法是什么,如果我决定按照上面展示的方式来解决这个问题,我是否有任何好的答案。
【问题讨论】:
-
你想从哪里访问 getParticleVertex() ?
-
所以我有另一个类 - ParticlesManage - 我想使用该类中的那个方法。在 ParticleManage 我只是有属性(现在): std::vector<:unique_ptr>> m_explodedParticles;
-
所以你不能直接调用 m_explodedParticles[some_index]->getParticleVertex() 吗?
-
但是我应该如何访问派生方法?使用多态时我不能这样做不是吗?
-
getParticleVertex() 仅在您扩展的 ParticlesVertex 类中定义,因此您的基类 ParticlesInterface 没有这样的功能。因此,在这里讨论多态是没有意义的。多态性的唯一用途是当您将 ParticlesInterface 对象的向量存储在某处时,但您将它们视为 ParticlesVertex,因为扩展是一种“是一种”关系(但反之则不然)。
标签: c++ inheritance sfml dynamic-binding