如何从接口获得派生类
How do I get the derived class from a interface?
在尝试在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,然后添加
相关文章:
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- 如何在基类中定义静态接口,并确保该接口必须在派生类中实现
- C 结构实现派生接口
- 如何从接口获得派生类
- 接口会议派生的类功能而无需铸造
- 共享接口类和 C++ 派生类中的默认参数值
- 在派生类接口中隐藏基类的特定函数
- C++ 从嵌套类的接口派生
- C#派生的接口在C++中无法正常工作
- 定义多个派生接口成员
- 从接口派生的模板 - 多态性停止工作
- 具有显式派生方法的C++接口
- 从Const引用接口到派生类的转换
- 如何创建从另一个派生的两个ATL接口
- CLR 探查器:COM 样式的强制转换和从派生接口调用函数
- 具有扩展接口的派生类的集合.如何在没有动态强制转换的情况下访问派生接口
- c++:通过基类接口构造派生对象
- IUknown 派生接口上的虚拟析构函数
- 为什么C++不允许基类实现派生类的继承接口?
- 如何使用包括派生接口在内的接口正确地公开C++API