您必須存儲基類指針或基類智能指針,並使用像boost:ptr_vector這樣的指針集合。
std::vector<television*> tv;
tv.push_back(new television);
tv.push_back(new BigTelevision);
// don't forget to delete
// better:
std::vector<std::unique_ptr<television>> tv;
tv.push_back(std::unique_ptr<television>(new television));
tv.push_back(std::unique_ptr<television>(new BigTelevision));
您現在可以通過通用接口(多態性)使用不同的對象。
class television
{
public:
// The interface for all television objects.
// Each television can calculate its price.
virtual int Price() const { return price_; }
private:
int price_;
};
class BigTelevision
{
public:
virtual int Price() const { return television::Price() * discount_; }
private:
double discount_;
};
int main()
{
std::vector<std::unique_ptr<television>> shoppingCard;
// add a basic television and a BigTelevision to my shopping card
shoppingCard.push_back(std::unique_ptr<television>(new television));
shoppingCard.push_back(std::unique_ptr<television>(new BigTelevision));
// whats the price for alle the tvs?
int price = 0;
for(auto tv = begin(shoppingCard), last = end(shoppingCard);
tv != last; ++tv)
price += (*tv)->Price();
// or:
int price = std::accumulate(begin(shoppingCard), end(shoppingCard), 0,
[](int sum, const std::unique_ptr<television>& tv)
{ return sum + tv->Price()});
}
爲什麼大電視需要由不同的班級代表?你需要爲大型電視模擬什麼不同的行爲? – 2012-02-18 11:22:19
BigTelevision作爲一個屬性可能有折扣,不管電視是否具有折扣。如果我使用它來存儲Bigtelevision類型,Television temp [20]將導致BigTelevision的某些屬性丟失。有什麼方法可以將兩種不同類型的東西作爲一個集合存儲在一起 – user1203499 2012-02-18 11:27:42
你可以在'television'類中擁有'b'成員,嘗試存儲這樣的內存毫無意義。除非你有幾千個「電視」。 – 2012-02-18 11:30:55