簡體   English   中英

在不丟失數據的情況下將子類對象存儲在同一容器中?

[英]Storing Child Class Objects in the Same Container without loosing data?

所以可以說我有一個叫做水果的基類,

class Fruit{

  public TYPE{ Apples, Oranges, Grapes, NoType };
  virtual int getType(){ return Fruit::TYPE::NoType; };
  virtual ~Fruits(){};

  virtual int randomFunc(){ return 991; };

}

然后說我有一個叫做Apple的孩子班,

class Apple : public Fruit{

  virtual int getType()override{ return Fruit::TYPE::Apples; };

  virtual int childFunc(){ return -1; };

}

現在,我的問題是,是否可以接收基類為Fruits的對象,並將各種子對象存儲在同一地圖/容器中,而又不丟失'childFunc()'功能或基函數中不存在的任何變量/函數? 理想情況下,我試圖找到類似的東西,

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.

}

可以將模板用於類似這樣的東西嗎? 這是普遍不贊成的做法嗎? 我使用單獨容器的問題是,我需要以先進先出的方式進行跟蹤。

std::shared_ptr<Fruit>在您的容器中。 若要查看是否可以依賴childFunct(),需要執行dynamic_cast<Apple *>(fruit.get()) ,其中fruit是std::shared_ptr<Fruit>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM