기본 클래스 포인터 또는 기본 클래스 스마트 포인터를 저장해야합니다. 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()});
}
왜 대형 텔레비전을 다른 클래스에서 나타내야합니까? 대형 TV에서 어떤 모델링을해야합니까? –
BigTelevision은 텔레비전에없는 것처럼 속성으로 할인을받을 수 있습니다. TV temp [20]는 Bigtelevision 유형을 저장하는 데 BigTelevision을 사용하면 일부 속성이 손실됩니다. 거기에 컬렉션으로 두 가지 유형을 함께 저장할 수있는 방법이 무엇입니까 – user1203499
'b' 멤버를'television' 클래스에 가질 수 있습니다. 그런 식으로 메모리를 절약하려고 할 필요는 없습니다. 않는 한 너는'텔레비전'의 수천을 가지고 가기 위하여려고하고 있지 않으면. –