如何在向量中存储具有不同类型的对象

时间:2017-02-07 17:21:33

标签: c++

我有三个继承自类组件的类。 在类Computer中,我想将这3个类的对象存储在向量中。

class Component {
public:
    double price;
    virtual void show() {
        std::cout << "Price: " << this->price << std::endl;
    }
};

class CPU : public Component {
public:
    double price;
    CPU(double price){ this->price = price; }
    void show() {
        std::cout << "CPU Price: " << this->price << std::endl;
    }
};

class RAM : public Component {
public:
    double price;
    RAM(double price){ this->price = price; }
    void show() {
        std::cout << "RAM Price: " << this->price << std::endl;
    }
};

class SSD : public Component {
public:
    double price;
    SSD(double price){ this->price = price; }
    virtual void show() {
        std::cout << "RAM Price: " << this->price << std::endl;
    }
};

class Computer : public Component {
public:
    std::vector<Component*> vec;
    void show() {
        for (auto el: vec) {
            std::cout << el->price << std::endl;
        }
    }
};

但是当我尝试这样做时,我看到那里的垃圾:

Computer c;
c.vec.push_back((Component*)new RAM(10));
c.show(); // garbage
std::cout << c.vec[0]->price << std::endl; // garbage

我在stackoverflow上读了几个关于这个的问题,但是我还是不明白我做错了什么。

1 个答案:

答案 0 :(得分:3)

问题在于您在每个子类中声明double price;。除了RAM::price之外,这还会创建单独的字段,即SSD::priceComponent::price。因此,当您构建new RAM(10)时,它只会将10分配给RAM::price,而不是Component::price。这就是你为什么要垃圾的原因。

要修复,只需删除所有这些额外的声明。

另外,为了帮助正确删除您创建的那些指针,我强烈建议使用智能指针向量(可能是std::vector<std::unique_ptr<Component>>)。然后你可以:

c.vec.push_back(std::make_unique<Component>(new RAM(10)));

并正常使用;当矢量被破坏时,指针将获得delete d。