【问题标题】:Printing variables of different derived class objects inside a single vector在单个向量中打印不同派生类对象的变量
【发布时间】:2022-01-15 17:44:34
【问题描述】:

所以我有一个包含一个基类和两个派生类的简单代码。每个派生类都有自己的变量,基类有一个 id 变量,应该与我从派生类创建的所有元素共享。

创建 2 个对象并将它们添加到向量中后,我只能打印它们的 ID。有什么方法可以从相应的元素中获取 a 和 b 变量? (例如:std::cout << items[0]->a;

class Item
{
public:
    int id;
    Item(int id) { this->id = id; }
};

class ItemTypeA : public Item
{
public:
    int a;
    ItemTypeA(int a, int id) : Item(id) { this->a = a; }
};

class ItemTypeB : public Item
{
public:
    int b;
    ItemTypeB(int b, int id) : Item(id) { this->b = b; }
};

int main()
{
    std::vector<std::shared_ptr<Item>> items;
    items.push_back(std::make_unique<ItemTypeA>(2, 0));
    items.push_back(std::make_unique<ItemTypeB>(3, 1));

    std::cout << items[0]->// I wanna print the a variable but it only lets me print the ID;

    return 0;
}

【问题讨论】:

    标签: c++ class constructor derived-class


    【解决方案1】:

    一种可能的解决方案是使用virtual 函数,如下例所示。看看下面的Print() 方法...

    class Item
    {
    public:
        int id; 
        Item(int id) { this->id = id; }
        virtual void Print(std::ostream& os) { os << id << " "; } 
    };
    
    class ItemTypeA : public Item
    {
    public:
        int a;
        ItemTypeA(int a, int id) : Item(id) { this->a = a; }
        void Print(std::ostream& os) override { Item::Print( os ); os << a << std::endl; }
    };
    
    class ItemTypeB : public Item
    {
    public:
        int b;
        ItemTypeB(int b, int id) : Item(id) { this->b = b; }
        void Print(std::ostream& os) override { Item::Print( os ); os << b << std::endl; }
    };
    
    int main()
    {
        std::vector<std::shared_ptr<Item>> items;
        items.push_back(std::make_unique<ItemTypeA>(2, 0));
        items.push_back(std::make_unique<ItemTypeB>(3, 1));
    
        for ( auto& el: items ) { el->Print(std::cout); }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-10
      • 2016-07-15
      • 1970-01-01
      • 2012-02-05
      • 2018-09-17
      • 2014-02-02
      相关资源
      最近更新 更多