C++基础类

标签 c++ class subclass

假设我有电视课和 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/

相关文章:

c++ - 原始 new[]/delete[] 与 std::vector 的优化

c++ - std::find on std::vector< std::string > 不能在 Visual C++ 2008 中编译?

c++ - 如何打印有序 C++ 字符串数组的直方图?

外部样式表中的 CSS 重用

Python:继承内置列表类型VS过滤器、map内置函数

nhibernate - Fluent NHibernate 尝试使用 table-per-subclass 映射子类的子类

c++ - 如何在 Windows 中的特定显示器上打开一个窗口?

c++ - qsort 类对象列表

zend-framework - Zend_Log 的 UML 类图是否正确?

ios - UIButton 子类忽略 'Touch Up Inside' 事件