基本クラスポインタまたは基本クラススマートポインタは、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()});
}
なぜ大きなテレビは別のクラスで表現する必要がありますか?大きなテレビのためにモデル化するためには、どのような異なる行動が必要ですか? –
BigTelevisionはテレビのように属性として割引を持つことがあります。私がBigtelevisionタイプを保存するために使用すると、テレビtemp [20]はBigTelevisionのいくつかの属性を失うことになります。コレクションとして2つの異なる型を一緒に格納する方法はありますか? – user1203499
'television'クラスに' b'メンバを置くことができます。そのようなメモリを節約しようとしても意味がありません。あなたが何千ものテレビを持っていない限り。 –