C++ 从基类函数派生的类容器
我想根据基类的派生类型更改基类中容器中对象的类型。(因此派生类认为它是指向类型“MyT:T”的指针的容器,而基类认为它正在存储指向类型“T”的指针。) 目前,我面临以下情况。我只是想知道是否有更好的解决办法 考虑这个最小的例子C++ 从基类函数派生的类容器,c++,inheritance,polymorphism,containers,C++,Inheritance,Polymorphism,Containers,我想根据基类的派生类型更改基类中容器中对象的类型。(因此派生类认为它是指向类型“MyT:T”的指针的容器,而基类认为它正在存储指向类型“T”的指针。) 目前,我面临以下情况。我只是想知道是否有更好的解决办法 考虑这个最小的例子 class Component { public: void Update(); }; class MyComponent: public Component { public: void Update() override {}; void D
class Component
{
public:
void Update();
};
class MyComponent: public Component
{
public:
void Update() override {};
void Draw();
};
class Foo
{
public:
std::vector<Component*> _components; //this container needs to return different types depending on which class is accessing it, so Foo gets a "Componeent*", and MyFoo gets a "MyComponent*.
void Update()
{
for (int i = 0; i < _components.size(); i++)
{
_components[i]->Update();
}
}
};
class MyFoo : public Foo //i guarantee that every pointer in the container in this derived class is of type "MyComponent" rather then "Component"
{
public:
void Draw()
{
for (int i = 0; i < _components.size(); i++)
{
((MyComponent*)_components[i])->Draw(); //how can i remove this cast? (every function in this class makes the same cast)
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
MyFoo test;
test.Update(); //should call the basic update
test.Draw(); //should call the draw of the derived type
//for clarification consider:
//test._components <- should be container of type "MyComponent*"
//((Foo)test)._components <- should be container of type "Component*"
// note that both examples above are thesame objects, all of actual type "MyComponent" becouse test is of class "MyFoo"
}
类组件
{
公众:
无效更新();
};
类MyComponent:公共组件
{
公众:
void Update()重写{};
无效抽取();
};
福班
{
公众:
std::vector _components;//此容器需要根据访问它的类返回不同的类型,因此Foo获得“component*”,MyFoo获得“MyComponent*”。
无效更新()
{
对于(int i=0;i<_components.size();i++)
{
_组件[i]->Update();
}
}
};
类MyFoo:public Foo//我保证这个派生类中容器中的每个指针的类型都是“MyComponent”,而不是“Component”
{
公众:
作废提款()
{
对于(int i=0;i<_components.size();i++)
{
((MyComponent*)\u components[i])->Draw();//如何删除此强制转换?(此类中的每个函数都进行相同的强制转换)
}
}
};
int _tmain(int argc,_TCHAR*argv[]
{
MyFoo试验;
test.Update();//应调用基本更新
test.Draw();//应调用派生类型的Draw
//关于澄清,请考虑:
//test.\u components好的,要从指向基类实例的指针中使用派生类函数,基类中的函数应该是virtual
。为此目的使用了函数。此外,您的组件
类必须声明Draw
方法,甚至可能是纯virtual
(即,virtual void Draw()=0
)如果函数在基类have中有定义没有意义。但是“Component”的每个派生类都需要是抽象的,或者有Draw.And“Component”的实现"它本身不能是一个实例。我希望组件是一个可实例化的类,并且我只希望对给定类有意义的方法可见。因此,如果我使用UpdateEstate函数创建MyComponent2:component,则该绘图在此上不可见,而MyComponent
禁用Update
函数我不是请确保这在不使用元编程的情况下是可能的。我不打算“隐藏”更新函数。示例已更新。请注意,“Foo”打算按照正常多态性的预期调用重写函数。