如何从接口获得派生类

How do I get the derived class from a interface?

本文关键字:派生 接口      更新时间:2023-10-16

在尝试在C 中创建实体 - 组件系统时,我因缺乏对语言的知识而面临一些问题。

使用类实体,保持接口 iComponent (它的作用更像是"我持有数据"的标志(,我有一个方法添加,如果已经存在同一类的另一个IComponent,则将组件添加到实体中。

这是一个过度简化的示例代码:

struct IComponent{};
struct Foo : IComponent{ int x;};
struct Bar : IComponent{ int y; };
class Entity{
    vector<IComponent*> entityComponents;
    void Add(IComponent* componentToAdd){
        if("entityComponents" does not contain the class of "componentToAdd")
            entityComponents.add (componentToAdd)
    }
}

我的预期结果是

Entity e;
Foo f;
Bar b;
Foo anotherF;
e.Add(f); // Works
e.Add(b); // Works
e.Add(anotherF); // Does not work because another 
                 //item in the array already inherits Foo

,但我不知道如何从iComponents列表内获取Foo和bar的基类,并检查它们是否重复。

我怎么能得到它们?如果FOO在ICOMPONENT列表中,我如何将IComponent施加到foo?

结帐dynamic_cast。您可以尝试将指针铸造为基类,以指向派生类的指针。如果实例化对象不是派生的类型,并且在这种情况下将返回null,则会失败。

如bar凳所说,我的解决方案是

template<typename T>
bool HasComponent(){
  for(Component* component: this->components)
        if(T* casted = dynamic_cast<T*>(component))
                return true;           
  return false;
}

和以后只检查" hascomponent(("是否为false,然后添加