[英]How to store objects with different types in a vector
I have three classes that inherit from the class component. 我有三个从类组件继承的类。 In class Computer I want to store objects of these 3 classes in a vector. 在计算机类中,我想将这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;
}
}
};
But when I try to do it I see the garbage there: 但是当我尝试这样做时,我看到那里的垃圾:
Computer c;
c.vec.push_back((Component*)new RAM(10));
c.show(); // garbage
std::cout << c.vec[0]->price << std::endl; // garbage
I read a few questions about this on the stackoverflow, but still don't understand what I'm doing wrong. 我在stackoverflow上读到了一些关于此的问题,但仍然不明白我在做什么错。
The problem is that you're declaring a double price;
问题是您要声明double price;
in each subclass. 在每个子类中。 This creates separate fields, ie RAM::price
and SSD::price
, in addition to Component::price
. 除了Component::price
之外,这还将创建单独的字段,即RAM::price
和SSD::price
Component::price
。 Thus, when you construct a new RAM(10)
, it only assigns 10
to RAM::price
, and not Component::price
. 因此,当您构造一个new RAM(10)
,它仅将10
分配给RAM::price
,而不是Component::price
。 That's why you're getting garbage. 这就是为什么您要垃圾的原因。
To fix, simply remove all those extra declarations. 要解决此问题,只需删除所有这些多余的声明。
Also, to aid with properly deleting those pointers you've created, I'd highly suggest using a vector of smart pointers (probably std::vector<std::unique_ptr<Component>>
). 另外,为帮助正确删除您创建的那些指针,我强烈建议使用一个智能指针向量(可能是std::vector<std::unique_ptr<Component>>
)。 Then you could just: 然后,您可以:
c.vec.push_back(std::make_unique<Component>(new RAM(10)));
and use it as normal; 并正常使用 the pointers will get delete
d when the vector is destructed. 向量被破坏时,指针将被delete
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.