您必须存储基类指针或基类智能指针,并使用像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