Exercise (FH): Write A Sensor Class: RandomSensor
¶
New Sensor Class: RandomSensor
¶
Based on the project you git-cloned in Exercise (FH): Introducing a Sensor Class,
extend the sensors
library (int src/sensors/
) with another
sensor, RandomSensor
.
Create two new files in that directory,
random-sensor.h
. That file contains the class definitionrandom-sensor.cpp
. That file contains the implementation
The proposed usage of such a sensor is as follows:
double low = 32.4;
double high = 38.7;
RandomSensor sensor{low, high};
double temperature = sensor.get_temperature();
// temperature is a random number between low and high
Here is a sample program that generates random numbers in such a
way. It is your responsibility to understand how random numbers are
generated, and to write the RandomSensor
class accordingly.
#include <random>
#include <iostream>
int main(int argc, char** argv)
{
if (argc != 3) {
std::cerr << argv[0] << ": <low> <high>" << std::endl;
return 1;
}
double low = std::stod(argv[1]);
double high = std::stod(argv[2]);
std::uniform_real_distribution<double> distribution(low, high); // <--- HERE
std::default_random_engine engine{std::random_device{}()}; // <--- HERE
while (true) {
double number = distribution(engine); // <--- HERE
std::cout << number << std::endl;
}
return 0;
}
Implementation Details¶
Like in the program above which uses two variables,
std::uniform_real_distribution<double> distribution(low, high);
std::default_random_engine engine;
… the RandomSensor
class will have to have two members,
class RandomSensor
{
// ...
private:
std::uniform_real_distribution<double> _distribution;
std::default_random_engine _engine;
};
The RandomSensor::get_temperature()
method uses these members to
generate random numbers in the specified range - exactly like the
program, but nicely encapsulated inside the method implementation.
The RandomSensor
constructor - RandomSensor(double low, double
high)
- passes its arguments to the constructor of the
_distribution
member in the initializer list.
See this in analogy to the class point
example in
A Live-Hacked Tour Around The New C++,
where we initialize int
members (and not random distributions),
class point
{
public:
point(int x, int y) : _x{x}, _y{y} {}
...
};
New Program: random-temperature.cpp
¶
In the firstname.lastname
directory you created for
Exercise (FH): Introducing a Sensor Class, create a new program,
random-temperature.cpp
that works just like this one,
but differs in the following ways:
It uses your
RandomSensor
implementation (and not theW1Sensor
)It takes from the commandline the necessary
low
andhigh
parameters to instantiate theRandomSensor
object (instead of thefilename
parameter that theW1Sensor
program uses). Theinterval
parameter is still necessary.$ ./random-temperature 10.5 30.1 1 ... spits out random numbers in the range [10.5, 30.1] every second ...