2012-02-18 69 views
0

可以说我有电视机类和BigTelevision类C++基本类

class television 
{ 
    protected: 
     int a; 
    ... 
} 
class BigTelevision:public television 
{ 
    private: 
    int b; 
... 
} 

我想包含混合电视和BigTelevision的集合,做什么选择我有。 我知道一种方法是使用数组,但问题是,如果我声明一个电视类型的数组来存储它们,BigTelevision的附加属性(例如int b)将会丢失。

我该如何解决这个问题?

+0

为什么大电视需要由不同的班级代表?你需要为大型电视模拟什么不同的行为? – 2012-02-18 11:22:19

+0

BigTelevision作为一个属性可能有折扣,不管电视是否具有折扣。如果我使用它来存储Bigtelevision类型,Television temp [20]将导致BigTelevision的某些属性丢失。有什么方法可以将两种不同类型的东西作为一个集合存储在一起 – user1203499 2012-02-18 11:27:42

+0

你可以在'television'类中拥有'b'成员,尝试存储这样的内存毫无意义。除非你有几千个“电视”。 – 2012-02-18 11:30:55

回答

4

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

} 
+0

我认为make_unique(..)不需要指向堆分配对象的指针 - 它创建一个并将其分配给std :: unique_ptr <..>。 //编辑:假设std :: make_unique <..>(..) – Simon 2012-02-18 12:05:38

+0

@Simon不幸的是,没有'std :: make_unique <>()'这样的东西' – inf 2012-02-18 13:14:48

+0

你是对的。我删除了make_unique调用..它不是标准的。 – hansmaad 2012-02-18 13:15:27

0

你会使用这两个类通用的方法吗?如果是这样,请使该方法虚拟并创建一个指向基类的指针数组。