Is possible create a queue for differents types of Objects, but with same interface?
As example, I have an interface called SensorItem, and 4 kinds of Class, SensorItemA ,SensorItemB, SensorItemC ,SensorItemD `
queue <SensorItem> cola;
void encolar(SensorItem* dato)
{
cola.push (*dato);
}
SensorItem* sacar()
{
SensorItem* d=cola.front();
cola.pop();
return d;
}
Thats my class Queue(Cola) and here i try to use it
void main()
{
Cola c=new Cola();
TemperatureItem t=new TemperatureItem(3.25);
c.encolar(t);
ImuItem i=new ImuItem(3,4,8);
}
its something wrong in my syntax? or just is not possible to do it?
Polymorphism in C++ only works with references and pointers. Objects in C++ are objects, not references. If you create a SensorItem
it will always be a SensorItem
, not a TemperatureItem
or a ImuItem
. If you have a std::queue<SensorItem>
, it's elements will always be SensorItem
s, never TemperatureItem
s or ImuItems
.
If you want to make a queue of objects derived from SensorItem
, you need to use a queue of pointers to SensorItem
s:
#include <iostream>
#include <queue>
#include <memory>
struct SensorItem
{
virtual void doAThing() = 0;
virtual ~SensorItem() {}
};
struct TemperatureItem : SensorItem
{
void doAThing() { std::cout << "TemperatureItem\n"; }
};
struct ImuItem : SensorItem
{
void doAThing() { std::cout << "ImuItem\n"; }
};
class Cola
{
private:
std::queue<std::unique_ptr<SensorItem>> cola;
public:
void encolar(std::unique_ptr<SensorItem> dato)
{
cola.push(std::move(dato));
}
std::unique_ptr<SensorItem> sacar()
{
std::unique_ptr<SensorItem> d = std::move(cola.front());
cola.pop();
return d;
}
};
int main()
{
Cola c;
c.encolar(std::make_unique<TemperatureItem>());
c.encolar(std::make_unique<ImuItem>());
std::unique_ptr<SensorItem> item = c.sacar();
item->doAThing();
item = c.sacar();
item->doAThing();
}
Here I've used std::unique_ptr
to avoid having to do manual memory management. You could use raw SensorItem*
s, but I would advise against it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.