[英]Storing Child Class Objects in the Same Container without loosing data?
So lets say I have a base class called Fruits, 所以可以说我有一个叫做水果的基类,
class Fruit{
public TYPE{ Apples, Oranges, Grapes, NoType };
virtual int getType(){ return Fruit::TYPE::NoType; };
virtual ~Fruits(){};
virtual int randomFunc(){ return 991; };
}
And then lets say I have a child class called Apple, 然后说我有一个叫做Apple的孩子班,
class Apple : public Fruit{
virtual int getType()override{ return Fruit::TYPE::Apples; };
virtual int childFunc(){ return -1; };
}
Now, my question, is it possible to receive an object with the base class Fruits, and store various child objects in the same map/container without loosing the 'childFunc()' functionality, or any variables/functions not existent in the base? 现在,我的问题是,是否可以接收基类为Fruits的对象,并将各种子对象存储在同一地图/容器中,而又不丢失'childFunc()'功能或基函数中不存在的任何变量/函数? Ideally I'm trying to find something like, 理想情况下,我试图找到类似的东西,
int FruitStorage::addFruit( Fruit* f, int i ){
this->fruitsMap[i] = *f; //I feel like receiving a base object will strip the child functionality.
return this->fruitsMap[i]->childFunc(); //I need to use the child functions after the object is stored.
}
Would it be possible to use templates for something like this? 可以将模板用于类似这样的东西吗? Is this a practice that's generally frowned upon? 这是普遍不赞成的做法吗? My issue with separate containers is that I need to track on a first-in-first-out basis. 我使用单独容器的问题是,我需要以先进先出的方式进行跟踪。
Store std::shared_ptr<Fruit>
in your container. 将std::shared_ptr<Fruit>
在您的容器中。 To see if you can rely on childFunct() you need to do a dynamic_cast<Apple *>(fruit.get())
where fruit is a std::shared_ptr<Fruit>
若要查看是否可以依赖childFunct(),需要执行dynamic_cast<Apple *>(fruit.get())
,其中fruit是std::shared_ptr<Fruit>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.