假设我有电视课和 BigTelevision 课
class television
{
protected:
int a;
...
}
class BigTelevision:public television
{
private:
int b;
...
}
我想包含电视和 BigTelevision 的混合集合,我有哪些选择。 我知道一种方法是使用数组,但问题是如果我声明一个电视类型数组来存储它们,BigTelevision 的附加属性(例如 int b)将会丢失。
我该如何解决这个问题?
最佳答案
您必须存储基类指针或基类智能指针或使用像 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));
您现在可以通过通用接口(interface)(多态性)使用不同的对象。
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()});
}
关于C++基础类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9340700/