Created
December 29, 2023 20:01
-
-
Save Micrified/6c0f6b7ff46038688b3edd704a1a1472 to your computer and use it in GitHub Desktop.
Sensors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <memory> | |
#include <vector> | |
class Sensor | |
{ | |
public: | |
enum Type | |
{ | |
ALTIMITER = 0, | |
ACCELEROMETER | |
}; | |
Sensor(Type t): | |
d_type(t) | |
{} | |
virtual ~Sensor(){} // Necessary to keep it polymorphic | |
const Type type() const | |
{ | |
return d_type; | |
} | |
protected: | |
Type d_type; | |
}; | |
class Accelerometer : public virtual Sensor | |
{ | |
public: | |
Accelerometer(double value): | |
Sensor(Sensor::Type::ACCELEROMETER), | |
d_acc(value) | |
{} | |
const double acceleration() const | |
{ | |
return d_acc; | |
} | |
private: | |
double d_acc; | |
}; | |
class Altimiter : public virtual Sensor | |
{ | |
public: | |
Altimiter(double value): | |
Sensor(Sensor::Type::ALTIMITER), | |
d_alt(value) | |
{} | |
const double altitude () const | |
{ | |
return d_alt; | |
} | |
private: | |
double d_alt; | |
}; | |
// ------------------------------------------------------------------------- // | |
void show_all(std::vector<std::shared_ptr<Sensor>>& v) | |
{ | |
for (std::shared_ptr<Sensor> s : v) | |
{ | |
switch (s->type()) | |
{ | |
case Sensor::Type::ALTIMITER: | |
std::cout << (std::dynamic_pointer_cast<Altimiter>(s))->altitude() | |
<< std::endl; | |
break; | |
case Sensor::Type::ACCELEROMETER: | |
std::cout << (std::dynamic_pointer_cast<Accelerometer>(s))->acceleration() | |
<< std::endl; | |
break; | |
default: | |
break; | |
} | |
} | |
} | |
int main () | |
{ | |
std::vector<std::shared_ptr<Sensor>> v; | |
v.push_back(std::make_shared<Accelerometer>(1.95)); | |
v.push_back(std::make_shared<Altimiter>(8.312)); | |
show_all(v); | |
return EXIT_SUCCESS; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment